我最近想跟蹤HTTPWebRequest
上傳進度的進度。所以我開始小,開始緩衝讀取一個簡單的文本文件。後來我發現,像在C中讀取(/寫入)文件#
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();
- 如何幫助自己,並解釋什麼是不按預期工作......? – 2010-11-21 04:38:04
@Mitch小麥,哦,我忘了添加錯誤,我更新了帖子。我得到'while'行的錯誤 – 2010-11-21 05:28:39