在C#中使用FileStream讀寫(xiě)文件,可以按照以下步驟進(jìn)行操作:
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()
{
// 創(chuàng)建FileStream對(duì)象
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);
// 寫(xiě)入文件
byte[] data = Encoding.UTF8.GetBytes("Hello, World!");
fileStream.Write(data, 0, data.Length);
// 關(guān)閉文件流
fileStream.Close();
}
}
上述代碼示例中,需要替換"filePath"為實(shí)際文件的路徑。