在C#中使用FileStream讀寫文件,可以按照以下步驟進行操作:
FileStream fileStream = new FileStream("filePath", FileMode.Open, FileAccess.ReadWrite);
byte[] buffer = new byte[1024];
int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
byte[] data = Encoding.UTF8.GetBytes("Hello, World!");
fileStream.Write(data, 0, data.Length);
fileStream.Close();
完整的代碼示例:
using System;
using System.IO;
using System.Text;
public class Program
{
public static void Main()
{
// 創建FileStream對象
FileStream fileStream = new FileStream("filePath", FileMode.Open, FileAccess.ReadWrite);
// 讀取文件
byte[] buffer = new byte[1024];
int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
string content = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine(content);
// 寫入文件
byte[] data = Encoding.UTF8.GetBytes("Hello, World!");
fileStream.Write(data, 0, data.Length);
// 關閉文件流
fileStream.Close();
}
}
上述代碼示例中,需要替換"filePath"為實際文件的路徑。