2013-02-25 79 views
1

我正在使用StreamReader,但如果嘗試使用兩個StreamReader對象讀取同一個流,則會出現一個錯誤消息,說我can't read from dispose object (reader3.ReadLine)。 由於我沒有處理任何對象,我在做什麼錯?StreamReader無法從處置對象中讀取

Stream responseStream2; 
FtpWebResponse ftpResponse2; 

string casefile = CNCElement.ID_CASE_TEST_FILE; 
string casepath; 
if (FileManager.PathCombine(result, lock_root_folder, casefile, out casepath) == false) 
    return false; 
if (fm.DownloadFtp(result, casepath, out responseStream2, out ftpResponse2) == false) 
    return false; 

StreamReader reader2 = new StreamReader(responseStream2); 
StreamReader reader3 = new StreamReader(responseStream2); 
byte[] contents=null; 
//if cycle is not present update case file 
//if cycle is present, case file is already correct 
if (reader2.ReadToEnd().Contains(cycle) == false) 
{ 
    byte seekcase = CNCElement.ID_CASE.Value; 
    int casecount = 1; 
    string line; 
    using (MemoryStream ms = new MemoryStream()) 
    { 
     while ((line = reader3.ReadLine()) != null 
       || casecount <= seekcase) 
     { 
      if (line.Contains("\"\"") == true) 
      { 
       if (casecount == seekcase) 
        line = line.Replace("\"\"", "\"" + cycle + "\""); 
      } 
      byte[] app = StrToByteArray(line); 
      ms.Write(app, 0, line.Length); 
      contents = ms.ToArray(); 
     } 
    } 
} 

if (reader2 != null) 
    reader2.Close(); 
if (ftpResponse2 != null) 
    ftpResponse2.Close(); 
+0

檢查流的有效性之前,從他們reding ...此外,爲什麼你會從同一個流讀兩次? – 2013-02-25 11:45:29

回答

3

當您閱讀到reader2的末尾時,您確實正在閱讀底層流的末尾(responseStream2)。此時從該流中讀取的另一個將失敗。

雖然稍微有些特殊的例外情況,但是在不同的StreamReaders中打包相同的流會做怪事,因爲這是一件很奇怪的事情。

如果您需要讀取兩次流,則需要使用支持將其位置重置爲開頭(即隨機訪問)的流,然後爲第二次讀取創建一個新讀取器;或者(在這種情況下看起來很可能:我懷疑任何網絡流將支持隨機訪問)自己緩衝流內容。

3

當你調用ReadToEnd()底層的蒸汽全部讀入內存,並且您已經走到了盡頭。

每次調用函數ReadLine()時,底層流都會移到下一行。

這意味着當您的應用程序到達Reader3.ReadLine()循環時,因爲您已經到達文件末尾,讀取器將失敗。

如果期望的文件流不是太大,我建議您將ReadToEnd()調用的結果分配給一個變量,並對該變量執行後續操作。

如果數據流很大,請嘗試重置Position屬性(假設它支持 - See the docs)。