How is the filestream used in C#?

In C#, the FileStream class is used for reading and writing files. It offers a set of methods and properties for manipulating files.

Here are some common methods and uses of the FileStream:

  1. Create a FileStream object.
  2. Create a new file stream named fs to open or create the file “file.txt”.
  3. Write data to a file.
  4. Convert the string “Hello, World!” into UTF-8 encoded bytes and write them to a file stream.
  5. Read file data:
  6. Create an array of bytes called buffer with a capacity of 1024. Read a maximum of 1024 bytes from the file system into the buffer and store the actual number of bytes read in the bytesRead variable. Convert the bytes in the buffer to a string using UTF-8 encoding, up to the number of bytes read, and store it in the content variable.
  7. Close the file stream.
  8. Close the file.
  9. Position the file pointer.
  10. Move the file pointer to the beginning of the file with fs.Seek(0, SeekOrigin.Begin).
  11. Truncate file.
  12. Clear the file content by setting its length to 0.

It is important to note that FileStream is a class that implements the IDisposable interface, so it is recommended to use the using statement to ensure that resources are automatically closed and released after use, like this:

using (FileStream fs = new FileStream("file.txt", FileMode.OpenOrCreate))
{
    // 在此进行读写文件的操作
}

This ensures that the file stream will be automatically closed and released when the code block ends.

bannerAds