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:
- Create a FileStream object.
- Create a new file stream named fs to open or create the file “file.txt”.
- Write data to a file.
- Convert the string “Hello, World!” into UTF-8 encoded bytes and write them to a file stream.
- Read file data:
- 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.
- Close the file stream.
- Close the file.
- Position the file pointer.
- Move the file pointer to the beginning of the file with fs.Seek(0, SeekOrigin.Begin).
- Truncate file.
- 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.