Curriculum
In C#, the FileStream class is used to read from and write to files in a low-level, sequential manner. It provides methods for reading and writing bytes to a file, as well as methods for seeking and setting the position within the file.
Here is an example of using FileStream to read from a file:
using System; using System.IO; class Program { static void Main() { string filePath = "example.txt"; byte[] buffer = new byte[1024]; using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { int bytesRead = fileStream.Read(buffer, 0, buffer.Length); while (bytesRead > 0) { // Process the bytes read from the file Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, bytesRead)); bytesRead = fileStream.Read(buffer, 0, buffer.Length); } } } }
In this example, we create a FileStream object by specifying the file path and FileMode.Open. We then use the Read method to read bytes from the file into a byte array buffer. The Read method returns the number of bytes read, which we use to check if we have reached the end of the file. If we have not reached the end of the file, we process the bytes read and continue reading from the file.
Here is an example of using FileStream to write to a file:
using System; using System.IO; class Program { static void Main() { string filePath = "example.txt"; byte[] buffer = Encoding.UTF8.GetBytes("Hello, World!"); using (FileStream fileStream = new FileStream(filePath, FileMode.Create)) { fileStream.Write(buffer, 0, buffer.Length); } } }
In this example, we create a FileStream object by specifying the file path and FileMode.Create. We then use the Write method to write bytes to the file from a byte array buffer.
Overall, FileStream is a useful class for reading and writing data to and from files in C#. It provides a low-level, efficient way to interact with file data, but it requires careful attention to detail and proper error handling to ensure that files are read and written correctly.