2012-08-27 129 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))