在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"为实际文件的路径。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>