How to use C# FileStream?

In C#, the FileStream class is used for reading and writing files. Here are some common usage methods:

  1. Create a FileStream object.
FileStream fileStream = new FileStream("example.txt", FileMode.OpenOrCreate);
  1. Read the content of the file:
byte[] buffer = new byte[1024];
int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
string content = Encoding.UTF8.GetString(buffer, 0, bytesRead);
  1. Write the content to a file.
string content = "Hello, world!";
byte[] buffer = Encoding.UTF8.GetBytes(content);
fileStream.Write(buffer, 0, buffer.Length);
  1. Close the FileStream object.
fileStream.Close();

When using FileStream, it is important to make sure to promptly close the file stream after the operation is complete to release resources. Additionally, resources can also be automatically released using the using statement, as shown below:

using (FileStream fileStream = new FileStream("example.txt", FileMode.OpenOrCreate))
{
    // 进行文件操作
}
bannerAds