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

标签 c# file-io

我最近想跟踪 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/

相关文章:

C# 相当于 imbue 和 numpunct

c# - 在C#中将数据写入CSV文件

c# - 如何使用 Entity Framework 扩展 BulkInsert 和 AllowDuplicateKeys

jquery - 当我使用PDO删除mysql数据库中的路径时如何删除图像

java - 为什么我无法从文件中读取字符串?

c# - MySqlHelper.Execute 异常 (C#) - 参数出现错误

c# - 如何为 Windows Phone 8.1 创建多个辅助磁贴

python - 如何返回具有精确定位的文本文件?

jquery - 如何使用 jQuery 在 div 中的文本后添加文件内容?

python - numpy.savetxt 可以用在 N>2 的 N 维 ndarray 上吗?