How to use C# FileStream Class

The FileStream Class serves as a representation of a file on a computer system. It provides functionality to perform operations such as reading from, writing to, opening, and closing files within a file system. Additionally, it enables manipulation of other file-related operating system handles, including pipes, standard input, and standard output.

One of the key features of the FileStream Class is its ability to facilitate the movement of data to and from the stream using arrays of bytes. This allows for efficient handling of file data, enabling operations such as reading a file's contents into memory or writing data from memory to a file. By working with byte arrays, developers have granular control over the manipulation of file data.

Some of FileModes as Follows :
  1. FileMode.Append : Open and append to a file if the file does not exist , it create a new file.

  2. FileMode.Create : Create a new file , if the file exist it will append to it.

  3. FileMode.CreateNew : Create a new File , if the file exist , it throws exception.

  4. FileMode.Open : Open an existing file.

How to create a file using C# FileStream Class?

To work with files using the FileStream Class, developers can utilize the FileMode enumeration, which provides various options for how files should be accessed or created. For instance, FileMode can specify whether a file should be opened for reading, writing, or both. It can also determine whether a new file should be created if it does not exist or whether an existing file should be overwritten.

The following C# example shows , how to create and write in a file using FileStream.

Full Source C#
using System; using System.Windows.Forms; using System.IO; using System.Text; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { System.IO.FileStream wFile; byte[] byteData = null; byteData = Encoding.ASCII.GetBytes("FileStream Test"); wFile = new FileStream("c:\\streamtest.txt", FileMode.Append); wFile.Write(byteData, 0, byteData.Length); wFile.Close(); } catch (IOException ex) { MessageBox.Show(ex.ToString()); } } } }

Through the use of the FileStream Class capabilities, developers can efficiently work with files and filesystem by implementing tasks such as arranging data into files and managing with the files handles as well as their access modes. This ability to access through files and the control of file operations to create an intricate and considerable functionality within C# applications is provided.

Conclusion

The FileStream Class in C# serves as a versatile tool for file manipulation, providing the ability to read from, write to, open, and close files on a file system. Through its integration with the FileMode enumeration, developers can precisely control file access and create, modify, or read file data efficiently using byte arrays.