StreamReader和StreamWriter是C#中用于處理文本文件的類,而FileStream是用于處理二進制文件的類。下面是它們的用法詳解:
StreamReader用法:
StreamReader reader = new StreamReader("file.txt");
StreamReader reader = new StreamReader(File.OpenRead("file.txt"));
string line = reader.ReadLine();
string content = reader.ReadToEnd();
reader.Close();
StreamWriter用法:
StreamWriter writer = new StreamWriter("file.txt");
StreamWriter writer = new StreamWriter(File.OpenWrite("file.txt"));
writer.Write("Hello");
writer.WriteLine("World");
writer.Close();
FileStream用法:
FileStream fileStream = new FileStream("file.bin", FileMode.Open, FileAccess.ReadWrite);
byte[] buffer = new byte[1024];
int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
byte[] data = { 0x01, 0x02, 0x03 };
fileStream.Write(data, 0, data.Length);
fileStream.Close();
以上就是StreamReader/StreamWriter與FileStream的用法詳解。根據具體需求和文件類型選擇適合的類來處理文件操作。