2010-11-21 168 views
2

我最近想跟蹤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(); 
+0

- 如何幫助自己,並解釋什麼是不按預期工作......? – 2010-11-21 04:38:04

+0

@Mitch小麥,哦,我忘了添加錯誤,我更新了帖子。我得到'while'行的錯誤 – 2010-11-21 05:28:39

回答

0

也許應該

outWriter.Write(buffer,0,read); 
+0

我想還有一個'BinaryWriter.Write(byte [])'http://goo.gl/or9l0 – 2010-11-21 05:31:13

+0

另外,爲什麼'offset'0?它應該是'bytesRead'而不是?否則循環,它會覆蓋寫入的數據? – 2010-11-21 05:48:44

+0

哦,也許你的意思是'inStream.Read(buffer,0,buffer.length)'? COS修復了這個問題 – 2010-11-21 06:33:36

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

由於您只需檢查上載操作的進度,您可以使用fileinfo對象檢查文件的大小。

在FileInfo類中,一個名爲length的屬性返回文件大小(以字節爲單位)。不知道當文件被寫入時它是否給出了當前的大小。但我認爲這是值得一試的,因爲它比你使用的方法更簡單,更高效。「同樣下面的代碼也不起作用。」