2012-08-27 54 views
0

我正在讀取一個二進制文件,並在等待發生的事情時,我注意到該程序沒有做任何事情。程序似乎不想讀取文件

它似乎被卡在某個執行點。我在一些打印語句中添加了控制檯,並且可以看到它達到某個特定點......但似乎並不想繼續。這是第一對夫婦的代碼行:

private BinaryReader inFile; 
public void Parser(string path) 
{ 
    byte[] newBytes; 
    newBytes = File.ReadAllBytes(path); 

    using (MemoryStream ms = new MemoryStream()) 
    { 
     ms.Write(newBytes, 0, newBytes.Length); 
     inFile = new BinaryReader(ms); 
     inFile.BaseStream.Seek(0, SeekOrigin.Begin); 
    } 
} 

public void ParseFile() 
{ 
    Console.WriteLine("parsing"); 
    Console.WriteLine("get size to read"); // prints this out 
    int sizeToRead = inFile.ReadInt32(); 
    Console.WriteLine("Size: {0}", sizeToRead); // doesn't print this out 
    Console.WriteLine("Done"); // end file processing 
} 

當我註釋掉讀取,它工作正常。我將​​的內容轉儲到一個新文件中,它與原始文件相同,所以它應該是一個有效的流。

我不知道如何繼續調試此問題。任何人遇到類似的問題?

編輯:對不起,我發佈了不同的方法和零件。下面是整個方法

+5

什麼是'inFile'? – CodingGorilla

+0

Yep同意@CodingGorilla將需要知道'inFile'是什麼,並且可以包含代碼嗎? –

+0

對不起,它只是一個'BinaryReader' – MxyL

回答

2

,處置了MemoryStream,使得您的BinaryReader無效。拋棄內存流將您的二進制閱讀器下拉出地毯。如果可以的話,將所有相關的閱讀代碼移到使用區塊中,並將BinaryReader也包含在其中。

using (var ms = new MemoryStream(File.ReadAllBytes(path))) 
using (var inFile = new BinaryReader(ms)) 
{ 
    inFile.ReadInt32(); 
} 

您可以從文件中直接讀取,除非你有充分的理由來讀這一切,並通過MemoryStream餵它。

如果您的代碼佈局方式使您不能使用using,那麼您可以跟蹤MemoryStreamBinaryReader對象並執行IDisposable。然後稍後調用Dispose`來清理。

垃圾收集器將清理最終如果你不這樣做,但什麼叫DisposeIDisposable好習慣進入。如果你不這樣做,你可能會遇到打開的文件句柄或GDI對象的問題,這些對象位於等待處置的終結器隊列中。

+0

無需在包裝時使用 – MethodMan

+0

正確。如果你不能使用'using'(比如在OP中的例子中),我只說跟蹤/處理流和閱讀器。 – BAF

+0

不是一個問題,它看起來有點令人困惑..但你有upvote良好的答案的方式..我也upvote :) – MethodMan

0

嘗試僅使用BinaryReader而不是使用FileStream(如果您是)。
如果這不起作用,請嘗試其他編碼選項,如Encoding.Unicode

 using (BinaryReader inFile = new BinaryReader(File.Open(@"myFile.dat", FileMode.Open),Encoding.ASCII)) 
     { 
      int pos = 0; 
      int length = (int)inFile.BaseStream.Length; 
      int sizeToRead; 
      while (pos < length) 
      { 
       Console.WriteLine("get size to read"); // prints this out 
       sizeToRead = inFile.ReadInt32(); 
       Console.WriteLine("Size: {0}", sizeToRead); // doesn't print this out, or anything after 
      } 
      Console.WriteLine("Done"); // end file processing 
     } 

如果還是不行,請嘗試使用File.OpenRead像這樣以避免在任何其他方式不是閱讀正在訪問的文件的可能性:一旦你離開using

using (BinaryReader inFile = new BinaryReader(File.OpenRead(@"myFile.dat"),Encoding.Unicode))