Udemy logo

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:

FileAccess Enumeration

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

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:

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.

Page Last Updated: April 2014

Top courses in C#

Complete C# Unity Game Developer 3D
Ben Tristem, Rick Davidson, GameDev.tv Team, Gary Pettie
4.7 (35,254)
Bestseller
RPG Core Combat Creator: Learn Intermediate Unity C# Coding
Ben Tristem, Rick Davidson, Sam Pattuzzi, GameDev.tv Team
4.8 (9,971)
Unity RPG Inventory Systems Asset Pack: Behind The Scenes
Sam Pattuzzi, GameDev.tv Team, Rick Davidson
4.6 (681)
C#/.NET - 50 Essential Interview Questions (Mid Level)
Krystyna Ślusarczyk
4.9 (61)
Highest Rated
C# Intermediate: Classes, Interfaces and OOP
Mosh Hamedani
4.5 (29,510)
Bestseller
Learn Parallel Programming with C# and .NET
Dmitri Nesteruk
4.5 (2,873)
Bestseller
Advanced Topics in C#
Dmitri Nesteruk
4.5 (246)
Design Patterns in C# and .NET
Dmitri Nesteruk
4.5 (9,452)
Bestseller
Complete C# Masterclass
Denis Panjuta, Tutorials.eu by Denis Panjuta
4.6 (20,944)

More C# Courses

C# students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.

Request a demo