FileStream Class in C#

FileStream Class

FileStream class can read and write operating system files.

FileStream can be used to perform the basic operations of reading and writing operating system files. To use this class, you must first declare a variable of the class FileStream.

To use this Class, you need to include the namespace:

Using System.IO

The class has many constructors; one of the constructors of this class takes the form:

public FileStream (string path, FileMode mode, bool ownsHandle);

This constructor takes its first argument the name or file or its path.

The second argument specifies the operation to perform on the file.

The third argument a Boolean value, indicating true if the file handle is owned by this FileStream instance; otherwise, false.

C# StreamWriter

StreamWriter class can be used to write text files. The StreamWriter class has several constructors and provides us with many methods. It is best placed in a using statement to ensure that the resources can be removed when no longer needed.

The class has several constructors; one of the constructors of this class takes:

public StreamWriter(Stream stream)

This constructor takes the first argument the stream, the stream which to write.

Example

FileStream fs = new FileStream(@"C:\Sample.txt", FileMode.OpenOrCreate,FileAccess.Write);
using (StreamWriter writer = new StreamWriter(fs))
{
    writer.Write("Sample Text "); 
}

Here, a new StreamWriter is initialized and the Write method writes the text Sample Text to the file. The Write method does not supply a new line. To add a new Line each time then, the WriteLine method must be supplied.

Advantages of “using” statement:

  1. Without, using you should manually dispose and close the StreamWriter.
  2. It will manage freeing of system resources if we are using “using” statement. 

StreamWriter Close()

If we did not specify the using statement then you should manually dispose and close the StreamWriter using the Close method:

FileStream fs = new FileStream((@"C:\Sample.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(fs); 

writer.Write("Hi.. This is the sample text file you have created using FileStream Class.");

writer.Close();

C# StreamReader

StreamReader reads text files. The namespace for it is System.IO namespace.

This class supplies several constructors, one of the constructors of this class:

public StreamReader (Stream stream)

This constructor takes the first argument the stream, the stream from which to read.

Example

FileStream fs = new FileStream(@"C:\Sample.txt", FileMode.OpenOrCreate, FileAccess.Read);
using (StreamReader reader = new StreamReader(fs))
{
   textBox1.Text = reader.ReadToEnd();              
}

Here, a new StreamWriter is initialized and the ReadToEnd() method reads the stream from the current position to the end of the stream.

Here's a basic example of how to use the FileStream class to read and write data to a file:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.txt"; // Replace with your file path
        
        // Writing to a file using FileStream
        using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
        {
            string contentToWrite = "Hello, FileStream!";
            byte[] dataToWrite = System.Text.Encoding.UTF8.GetBytes(contentToWrite);
            
            fileStream.Write(dataToWrite, 0, dataToWrite.Length);
        }
        
        // Reading from a file using FileStream
        using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
            
            string contentRead = System.Text.Encoding.UTF8.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Content read from file: " + contentRead);
        }
    }
}

In this example, the code demonstrates how to create a FileStream for writing and reading data to/from a file named "example.txt". The using statement ensures that the FileStream is properly closed and resources are released after its usage.

Remember to replace "example.txt" with the actual path to the file you want to work with. Also, error handling and proper disposal of resources are important in production code, so consider adding those aspects to your implementation.

Conclusion

In this article, I have discussed how to read and write text files using the FileStream class, and the advantages of “using” statement to manage the disposing and closing of resources automatically.