文件读写的FileStream

各省高考 2025-01-04 10:27:33

在C中,FileStream类提供了对文件进行读写操作的强大功能。它允许开发者以字节流的方式访问文件,从而实现灵活而高效的文件处理。

文件读写的FileStream文件读写的FileStream


读文件

要从文件中读取数据,可以使用FileStream类的Read()方法。该方法将字节块读入提供的缓冲区中,并返回实际读取的字节数。开发者可以多次调用Read()方法,直到读取完文件中的所有字节。

例如,以下代码从名为"file.txt"的文件中读取内容:

```csharp using System.IO;

namespace FileStreamExample { class Program { static void Main(string[] args) { using (FileStream fileStream = new FileStream("file.txt", FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[1024]; int bytesRead;

while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0) { // 处理读取的字节 } } } } } ```

写文件

要向文件中写入数据,可以使用FileStream类的Write()方法。该方法将字节块从提供的缓冲区中写入到文件中。与Read()方法类似,开发者可以多次调用Write()方法,直到写入完所有字节。

例如,以下代码向名为"file.txt"的文件中写入内容:

```csharp using System.IO;

namespace FileStreamExample { class Program { static void Main(string[] args) { using (FileStream fileStream = new FileStream("file.txt", FileMode.Create, FileAccess.Write)) { byte[] buffer = new byte[1024]; string data = "Hello world!";

// 将数据转换为字节数组 byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(data);

// 将字节数组写入文件 fileStream.Write(dataBytes, 0, dataBytes.Length); } } } } ```

使用注意事项

使用FileStream类时,需要注意以下几点:

版权声明:本文内容由互联。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发 836084111@qq.com 邮箱删除。