Basics of FileStream in C#

The FileStream is a class used for reading and writing files in C#. 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.

The Syntax to declare a FileStream object is given as

FileStream fileObj = new FileStream(file Name/Path, FileMode.field, FileAccess.field, FileShare.field);

Parameter Description Fields
Name of the File Name of the file you want to work with along with its extension or the complete path of the file. Eg: FileName.txt, @”C:\Users\Username\Documents\FileName.txt”
FileMode It specifies which mode the file has to be opened in. Open – To open an existing file
Create – To create a new file if the same file name already exists it will be overwritten
OpenOrCreate – To open a file if it exists else create new if it doesn’t
Create – To specifically create a new file
Append – To open an existing file and append more information at the end of the file. If the file doesn’t exist a new file will be created
Truncate – To open a existing file and truncate its size to Zero bytes
FileAccess It specifies the access to the file. – Read – To read data from a file
– Write – To write data to a file
– ReadWrite – To read and write data to a file
FileShare It specifies the access given to other FileStream objects to this particular file – None – To decline the sharing of the file. Any access request will fail until the file is closed.
– Read – To allow subsequent reading of the file.
– Write – To allow subsequent writing to the file.
– ReadWrite – To allow subsequent reading and writing of the file.
– Delete – To allow subsequent deleting of the file.
– Inheritable – To allow the file handle inheritable by child processes.

Example: In the code given below we write and read some text to a text file. To write the text first create an object of the FileStream class in Create mode and Write access. Store the text you want to write in a variable of type var, it is a keyword used to declare implicit types.

Next, create a byte array and encode the text into UTF8 which is an encoding standard capable of encoding all 1, 112, 064 valid character code points in Unicode. Then using the Write() method write to the text file. The Write() method’s parameters are the byte array to write from, the offset of the text file, and the length of the text. Lastly, close the FileStream object using Close().



To read the text file we create a FileStream object in Open mode and Read access. Declare a byte array to read from the text file and an integer to keep the count of the bytes. Using the Read() method read from the text file. The Read() method’s parameters are the byte array, offset of the text file from where to begin reading, and the length of the text that has to be read. Lastly using GetString() write the read text from the byte array to the console.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to write and read from 
// a text file using FileStream class
using System;
using System.IO;
using System.Text;
   
namespace FileStreamWriteRead {
   
class GFG {
   
    static void Main(string[] args)
    {
        // Create a FileStream Object
        // to write to a text file
        // The parameters are complete 
        // path of the text file in the 
        // system, in Create mode, the
        // access to this process is 
        // Write and for other 
        // processes is None
        FileStream fWrite = new FileStream(@"M:\Documents\Textfile.txt",
                     FileMode.Create, FileAccess.Write, FileShare.None);
   
        // Store the text in the variable text
        var text = "This is some text written to the textfile "+
                       "named Textfile using FileStream class.";
   
        // Store the text in a byte array with
        // UTF8 encoding (8-bit Unicode 
        // Transformation Format)
        byte[] writeArr = Encoding.UTF8.GetBytes(text);
   
        // Using the Write method write
        // the encoded byte array to
        // the textfile
        fWrite.Write(writeArr, 0, text.Length);
   
        // Closee the FileStream object
        fWrite.Close();
   
        // Create a FileStream Object
        // to read from a text file
        // The parameters are complete
        // path of the text file in 
        // the system, in Open mode,
        // the access to this process is
        // Read and for other processes
        // is Read as well
        FileStream fRead = new FileStream(@"M:\Documents\Textfile.txt"
                       FileMode.Open, FileAccess.Read, FileShare.Read);
   
        // Create a byte array 
        // to read from the 
        // text file
        byte[] readArr = new byte[text.Length];
        int count;
   
        // Using the Read method 
        // read until end of file
        while ((count = fRead.Read(readArr, 0, readArr.Length)) > 0) {
            Console.WriteLine(Encoding.UTF8.GetString(readArr, 0, count));
        }
   
        // Close the FileStream Object
        fRead.Close();
        Console.ReadKey();
    }
}
}

chevron_right


Output:

filetstream read and write in C#




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.