用C#读取(/写入)文件

时间:2010-11-21 04:26:25

标签: c# file-io

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

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

变成类似下面的东西,包括所有的流,读者,作家等。或者可以删除某些东西?此外,下面的代码不起作用。也许我做错了什么,是什么方式阅读(我猜写会相似)到缓冲区,以便我可以跟踪进度,假设流不是本地的,例如。的WebRequest

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();

3 个答案:

答案 0 :(得分:0)

应该是

outWriter.Write(buffer,0,read);

答案 1 :(得分:0)

由于你似乎正在阅读文本(尽管我可能错了),如果你逐字逐句地阅读而不是调用标准的Read(),你的程序似乎会简单得多:

BinaryReader reader = new BinaryReader(File.Open("./text.txt", FileMode.Open));
MemoryStream outStream = new MemoryStream();
StreamWriter outWriter = new StreamWriter(outStream);

while (Reader.BaseStream.Position < Reader.BaseStream.Length)
{
    outWriter.Write(reader.ReadChar());
    Debug.WriteLine("Progress: " + ((double)reader.BaseStream.Position) / (double)(reader.BaseStream.Length) + "%");
}
outWriter.Close();
txtLog.Text = outStream.ToString();

答案 2 :(得分:0)

由于您只需要检查上传操作的进度,您只需使用fileinfo对象检查文件的大小。

在FileInfo类中,有一个名为length的属性,它返回以字节为单位的文件大小。不确定它是否在写入文件时给出当前大小。但我认为值得一试,因为它比你正在使用的方法更简单有效