gpt4 book ai didi

c# - 是否可以每次读取一定数量的文件?

转载 作者:太空宇宙 更新时间:2023-11-03 23:03:20 24 4
gpt4 key购买 nike

在 C# 中,是否可以在每次执行 read 时只从文件中读取一定数量的字节数据?它将完成与下面的 python 代码行相同的事情

data=file.read(1024)

其中 1024 是它读取的字节数。

data 将返回一个包含文件中 1024 字节文本的字符串。

C# 有什么东西可以完成同样的事情吗?

最佳答案

你像这样以 1024 字节的 block 读取文件:

string fileName = @"Path to the File";
int bufferCapacity = 1024;
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[bufferCapacity ]; // will contain the first 1024 bytes
fs.Read(buffer, 0, bufferCapacity);
}

最后 buffer 将包含所需的字节,要将它们转换为字符串,您可以使用以下代码行:

var stringData = System.Text.Encoding.UTF8.GetString(buffer);

给你的附加说明,如果你需要从文件中获取前 n 行意味着你可以使用以下行:

 List<string> firstNLines = File.ReadLines(fileName).Take(n).ToList();

关于c# - 是否可以每次读取一定数量的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42266163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com