FileStream Class in C#

FileStream Class in C# with Examples

In this article, I am going to discuss FileStream Class in C# with Examples. Please read our previous article where we discussed the basics of File Handling in C#.

What is FileStream Class in C#?

The FileStream class in C# provides a stream for file operations. It can be used to perform both synchronous and asynchronous read and write operations. With the help of FileStream class, we can easily read and write data into files.

How to use FileStream Class in C#?

In order to use FileStream class in C#, first of all, we need to include the System.IO namespace and then we need to create an instance of the FileStream object to create a new file or open an existing file. If you go to the definition of FileStream class, you will see that there are many overloaded versions of Constructors available as shown in the below image.

How to use FileStream Class in C#?

The simplest way to create an instance of FileStream class is to use the following overloaded version of the Constructors.

public FileStream(string path, FileMode mode): This Constructor Initializes a new instance of the FileStream class with the specified path and creation mode.

Here,

  1. path: A relative or absolute path for the file that the current FileStream object will encapsulate.
  2. mode: A constant that determines how to open or create the file.

public FileStream(string path, FileMode mode, FileAccess access): This overloaded version initializes a new instance of the FileStream class with the specified path, creation mode, and read/write permission.

Here,

  1. path: A relative or absolute path for the file that the current FileStream object will encapsulate.
  2. mode: A constant that determines how to open or create the file.
  3. access: A constant that determines how the file can be accessed by the FileStream object. This also determines the values returned by the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties of the FileStream object. System.IO.FileStream.CanSeek is true if the path specifies a disk file.

public FileStream(string path, FileMode mode, FileAccess access, FileShare share): This overloaded version is Initializes a new instance of the System.IO.FileStream class with the specified path, creation mode, read/write permission, and sharing permission.

  1. path: A relative or absolute path for the file that the current FileStream object will encapsulate.
  2. mode: A constant that determines how to open or create the file.
  3. access: A constant that determines how the file can be accessed by the FileStream object. This also determines the values returned by the System.IO.FileStream.CanRead and System.IO.FileStream.CanWrite properties of the FileStream object. System.IO.FileStream.CanSeek is true if the path specifies a disk file.
  4. share: A constant that determines how the file will be shared by processes.

Let us discuss FileMode. FileAccess, and FileShare in detail.

FileMode in C#:

The FileMode specifies how the operating system should open a file. If you go to the definition of FileMode, then you will see that it is an enum with the following structure.

FileMode in C#

It has the following six constant values.  

  1. CreateNew: It specifies that the operating system should create a new file. This requires System.Security.Permissions.FileIOPermissionAccess.Write permission. If the file already exists, a System.IO.IOException exception is thrown.
  2. Create: It specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires System.Security.Permissions.FileIOPermissionAccess.Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use System.IO.FileMode.CreateNew; otherwise, use System.IO.FileMode.Truncate. If the file already exists but is a hidden file, an System.UnauthorizedAccessException exception is thrown.
  3. Open: It specifies that the operating system should open an existing file. The ability to open the file is dependent on the value specified by the System.IO.FileAccess enumeration. A System.IO.FileNotFoundException exception is thrown if the file does not exist.
  4. OpenOrCreate: It specifies that the operating system should open a file if it exists; otherwise, a new file should be created. If the file is opened with FileAccess.Read, System.Security.Permissions.FileIOPermissionAccess.Read permission is required. If the file access is FileAccess.Write, System.Security.Permissions.FileIOPermissionAccess.Write permission is required. If the file is opened with FileAccess.ReadWrite, both System.Security.Permissions.FileIOPermissionAccess.Read and System.Security.Permissions.FileIOPermissionAccess.Write permissions are required.
  5. Truncate: It specifies that the operating system should open an existing file. When the file is opened, it should be truncated so that its size is zero bytes. This requires System.Security.Permissions.FileIOPermissionAccess.Write permission. Attempts to read from a file opened with FileMode.Truncate causes a System.ArgumentException exception.
  6. Append: It opens the file if it exists and seeks the end of the file, or creates a new file. This requires System.Security.Permissions.FileIOPermissionAccess.Append permission. FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek a position before the end of the file throws a System.IO.IOException exception, and any attempt to read fails and throws a System.NotSupportedException exception.
FileAccess in C#:

It gives permission to file for read, write, or read/write access. If you go to the definition of FileAccess, then you will see that it is an enum with the following structure.

FileAccess in C#

It has the following three constant values.  

  1. Read– It gives read access to the file. Data can be read from the file. Combine with Write for read/write access.
  2. Write – It gives Write access to the file. Data can be written to the file. Combine with Read for read/write access.
  3. ReadWrite – It gives read and writes access to the file. Data can be written to and read from the file.
FileShare in C#:

It contains constants for controlling the kind of access other FileStream objects can have to the same file. That means it opens a file with share permission. If you go to the definition of FileShare, you will see that it is an enum with the following structure.

FileShare in C#

It has the following six constant values.

  1. None: Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.
  2. Read: Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
  3. Write: Allows subsequent opening of the file for writing. If this flag is not specified, any request to open the file for writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
  4. ReadWrite: Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.
  5. Delete: Allows subsequent deleting of a file.
  6. Inheritable: Makes the file handle inheritable by child processes. This is not directly supported by Win32.
Example to Understand FileStream class in C#:

In the below example, we will create a new file called “MyFile.txt” and saves it on the disk. And then we will open this file, saves some text in it, and then close this file.

File Creation Example using FileSteam Class in C#:

In the below example, first, we created an instance of FileStream class to create a new MyFile.txt file in the D drive.

using System;
using System.IO;
namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Set the File Path
            string FilePath = @"D:\MyFile.txt";
            FileStream fileStream = new FileStream(FilePath, FileMode.Create);
            fileStream.Close();
            Console.Write("File has been created and the Path is D:\\MyFile.txt");
            Console.ReadKey();
        }
    }
}

When you run the above code, you will get the following output.

File Creation Example using FileSteam Class in C#

File Open and Write Example using FileSteam Class in C#:

The MyFile.txt file is created on the D drive. Now we will open this file and we will write some text in it. In the below example, first, we created an instance of FileStrem class. Then Encoded a string into bytes and kept it into byte[] variable bdata and finally using Write() method of FileStream stored the string into the file.

using System;
using System.IO;
using System.Text;

namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Set the File Path
            string FilePath = @"D:\MyFile.txt";
            FileStream fileStream = new FileStream(FilePath, FileMode.Append);
            byte[] bdata = Encoding.Default.GetBytes("C# Is an Object Oriented Programming Language");
            fileStream.Write(bdata, 0, bdata.Length);
            fileStream.Close();
            Console.WriteLine("Successfully saved file with data : C# Is an Object Oriented Programming Language");
            Console.ReadKey();
        }
    }
}

When you run the above code, you will get the following output.

File Open and Write Example using FileSteam Class in C#

File Read Example using FileStream Class in C#:

We have already created one MyFile.txt and also, we also we have written some data into it. Now, we will see, how to read the data from the MyFile.txt file. In the below example, we have opened the file with the Read permission and used StreamReader class to read the file and then print the data in the console.

using System;
using System.IO;
namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string FilePath = @"D:\MyFile.txt";
            string data;
            FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
            using (StreamReader streamReader = new StreamReader(fileStream))
            {
                data = streamReader.ReadToEnd();
            }
            Console.WriteLine(data);
            Console.ReadLine();
        }
    }
}

When you run the above code, you will get the following output.

File Read Example using FileStream Class in C#

Note: The FileStream class in C# is used for reading and writing files. It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare.

In the next article, I am going to discuss StreamReader and StreamWriter Class in C# with examples. Here, in this article, I try to explain FileStream Class in C# with examples. I hope you enjoy this FileStream Class in C# with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.