C# FileStream: Accessing Files and Other IO

c sharp filestreamC# is a modern object oriented programming language. It was developed by Microsoft as a response to Java, and a way to further their .NET framework. Owing to the popularity of the .NET framework, C# programmers are in great demand in the industry. So it’s a good idea to brush up your C# skills – or even to learn it afresh. If you’re familiar with Java or C++, it’ll be rather easy to learn C#. If you’re new to programming, you can start with this beginners course on C#.

FileStream forms part of the Stream class in C#. The Stream class can be used to accomplish both read and write operations, which can be done both in synchronous and asynchronous modes. The Microsoft .Net framework supports two other classes – MemoryStream and NetworkStream – besides of course FileStream. There also is the BufferedStream that caters for buffered Input and Output operation in the .Net framework. You can learn more about the different kind of streams in C# with this course.

FileStream allows the programmer to have access to the standard input, output and error streams for files. Also, being a descendant of the Stream class, the FileStream class inherits all the methods and properties of the Stream class besides also adding some of its own. FileStream has two new methods of its own – Lock and Unlock. The Lock method, as its name signifies binds the files to the current process exclusively, preventing any other process to have access to the file while it is being used. Similarly, the Unlock method is used to unlock the files from the current process . Now let’s look into  few programs to see how this all comes together.

Example 1: Simple Program to Demo Using FileStream Class in C#

using System.IO;
FileStream fileStream = new FileStream(FilePath, FileMode.Open,FileAccess.Read, FileShare.ReadWrite);
try
{
    // Code to perform some operation
}
finally
{
   fileStream.Close();
}

The first statement here tells the system we’re going to be using the System.IO. The second statement actually creates a new filestream. Note the various parameters you have to specify while opening the filestream. We cover them later in this tutorial. However, if you’d like a sneak peak, hop over to this intermediate C# course to lean more about them.

Example 2: Program to Depict Use of FileStream in Accessing File Object

    using System;
    using System.IO;
    namespace ConsoleApplication1
    {
    class Program
    {
        static void Main(string[] args)
             {
             FileStreamMyFileStream = null;
             try
                 {
                 MyFileStream = new FileStream("c:\Tom.dat", FileMode.Create, FileAccess.Read);
                 Console.WriteLine("Tom.dat created successfully");
                 }
             catch (Exception e)
                 {
                 WriteLine("Failed to create file with the following error: " + e.Message);
                 }
             finally
                 {
                 MyFileStream.Close();
                 }
         }
         }
    }
Output:
Tom.dat successfully created, check the local folder! Press any key to continue . . .

This is a simple program that shows how to create a filestream, and also check for an error condition. After creating the filestream, note that we have a few lines to capture any exceptions, and print an error message on the screen.

Example 3: How to Create a New File and Perform Read and Write Operations on the File

 using System;
 using System.IO;
 namespace FileStreamSampleCS
 {
 class Program
 {
 static void Main(string[] args)
 {
 FileStreamMyFileStream = null;
 try
 {
 try
 {
 MyFileStream = new FileStream("c:\Tom.dat", FileMode.Create, FileAccess.ReadWrite);
 Console.WriteLine("Tom.dat file created successfully");
 }
 catch (Exception e)
 {
 throw new Exception("Failed to create/open filestream with error: " + e.Message);
 }
 catch (Exception e)
 {
 throw new Exception("Read failed with error: " + e.Message);
 }
 if (BytesRead == 0)
 {
 Console.WriteLine("No more bytes to read");
 break;
 }
 }
 }
 finally
 {
 MyFileStream.Close();
 Console.WriteLine("Close() is OK");
 }
 }
 }
 }
Output:
Tom.dat file created successfully
No more bytes to read
Close<> is OK
Press any key to continue . . .

Notice that this is pretty similar to Example2. But this time around, we’ve added in a few lines to read the file, and close it only once the read is complete. To see other similar examples using FileStream, check out this C# tutorial.

Other than the methods we showed above, the FileStream also has nine overloaded constructors that allow the programmer to have more control over the files states. This includes setting up various access permissions as well as creation states using enumerations such as FileMode, FileAccess and FileShare.

FileMode Enumeration

The FileMode enumeration allows the programmer to specify the mode in which the file is to be opened. This mode can be used to perform the following actions:

  • Append: this will open the file if it exists and seeks the end of the file where new data is to be added. If the file does not exists, this will create a new file.  Also, the Append mode can be used only when the FileAccess.Write permission is true.
  • Create: this will create a new file. However, if the file name used matches with an existing file, it will overwrite the pre-existing file.
  • CreateNew: creates a new file.
  • Open: opens an existing file.
  • OpenorCreate: this will open a file if it already exists or will create a new one if it is not existing.
  • Truncate: this will open an existing file and truncate its size to zero.

FileAccess Enumeration

The FileAccess Enumeration sets the mode of accessing a file as the situation demands. Actions that this mode allows for include:

  • Read: allows performing read operation only and not writing.
  • Write: allows for only write operation and not reading.
  • ReadWrite: will allow for both read and write operations.

FileShare Enumeration

The FileShare Enumerations comes in handy in situations when the file is required to be shared with any other process. For instance, if the Asp.Net application sources its data from a database and the FileAccess enumeration is not set then only one user will have access to the database. Others trying to access the database will be served an error message, a scenario least likely in a commercial application where there could be hundreds or even thousands who need to have access to the database simultaneously. The FileShare Enumeration allows the following actions:

  • None: allows exclusive access to the file. Other will have access only when it is closed. This is the default setting.
  • Read: Will allow for opening of the file but it will be only for reading purpose.
  • Write: Will allow for opening the file but only for writing purpose.
  • ReadWrite: Will allow for opening the file for both read and write operations.

Example 4: How to Flush a stream

using System;
using System.IO;
namespace FileHandlingExample2
{
class Program
{
static void Main(string[] args)
{
FileStreamfileStream = new FileStream(@"C:\DemoFile.txt",FileMode.Append,FileAccess.Write);
StreamWriterstreamWriter = new StreamWriter(fileStream);
streamWriter.Write("Hello");
streamWriter.Flush();
Console.WriteLine("File is saved");
Console.ReadKey();
}
}
}

In this program, object streamWriter that belongs to StreamWriter Class is created and is provided with the attributes of the fileStream object. Thereafter, streamwriterobject is used to call write class and write int the file that is selected or created. Lastly, Flush is used to save the file. If we hadn’t used Flush, the data would have been stored in the dynamic memory, where it would remain only for the duration of the program execution and will get deleted once the program is closed.

In this article we’ve walked you through the FileStream class and the ways it can be used. We’ve covered the basic methods along with examples. However, there’s a lot more to be learned. Play around with the code on your own and try out various methods. Once you’re ready to move on to the next level, you can also try creating your own Android App in C# with this course.