gpt4 book ai didi

c# - 在 C# 中读取(/写入)文件

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

我最近想跟踪 HTTPWebRequest 的上传进度。所以我从小处着手,从缓冲读取一个简单的文本文件开始。然后我发现像

这样的简单任务
File.ReadAllText("text.txt");

变成像下面这样的东西,包括所有的流、读者、作者等。或者可以删除一些东西吗?下面的代码也不起作用。也许我做错了什么,假设流不是本地的,那么读取(我想写入将是相似的)到缓冲区的方式是什么,以便我可以跟踪进度。 Web请求

byte[] buffer = new byte[2560]; // 20KB Buffer, btw, how should I decide the buffer size?
int bytesRead = 0, read = 0;
FileStream inStream = new FileStream("./text.txt", FileMode.Open, FileAccess.Read);
MemoryStream outStream = new MemoryStream();
BinaryWriter outWriter = new BinaryWriter(outStream);

// I am getting "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."
// inStream.Length = Length = 9335092
// bytesRead = 2560
// buffer.Length = 2560
while ((read = inStream.Read(buffer, bytesRead, buffer.Length)) > 0)
{
outWriter.Write(buffer);
//outStream.Write(buffer, bytesRead, buffer.Length);
bytesRead += read;
Debug.WriteLine("Progress: " + bytesRead / inStream.Length * 100 + "%");
}
outWriter.Flush();

txtLog.Text = outStream.ToString();

更新:解决方案

byte[] buffer = new byte[2560];
int bytesRead = 0, read = 0;
FileStream inStream = File.OpenRead("text.txt");
MemoryStream outStream = new MemoryStream();

while ((read = inStream.Read(buffer, 0, buffer.Length)) > 0)
{
outStream.Write(buffer, 0, buffer.Length);
bytesRead += read;
Debug.WriteLine((double)bytesRead / inStream.Length * 100);
}

inStream.Close();
outStream.Close();

最佳答案

应该是

outWriter.Write(buffer,0,read);

关于c# - 在 C# 中读取(/写入)文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4236436/

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