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
}

当我评论阅读时,它工作正常。我将 的内容转储inFile到一个新文件中,它与原始文件相同,所以它应该是一个有效的流。

我不确定如何继续调试此问题。有人遇到过类似的问题吗?

编辑:对不起,我发布了一些不同的方法。这是整个方法

4

2 回答 2

2

一旦你离开using街区,MemoryStream就会被处置,BinaryReader也使你无效。扔掉内存流就是从二进制阅读器下面拉出地毯。如果可以的话,将所有相关的阅读代码移动到一个 using 块中,并将你的代码也包含在一个块BinaryReader中。

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

您也可以直接从文件中读取,除非您有理由将其全部读入并通过MemoryStream.

如果您的代码布局方式使您无法使用using,那么您可以跟踪MemoryStreamBinaryReader对象并实现IDisposable。然后稍后对它们调用 Dispose 以进行清理。

如果你不这样做,垃圾收集器最终会清理干净,但是调用Dispose任何IDisposable是好习惯的东西。如果不这样做,您可能会遇到打开文件句柄或 GDI 对象在终结器队列中等待处理的问题。

于 2012-08-27T19:42:59.750 回答
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 (BinaryReader inFile = new BinaryReader(File.OpenRead(@"myFile.dat"),Encoding.Unicode))
于 2012-08-27T19:02:43.917 回答