I was reading a binary file and while waiting for something to happen, I noticed that the program wasn’t doing anything.
It seemed to be stuck at a certain point in execution. I added in some print statements to console, and can see that it gets to a certain point…but then doesn’t seem to want to continue. This is the first couple lines of code:
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
}
When I comment out the read, it works fine. I dumped the contents of inFile into a new file and it was the same as the original file, so it should be a valid stream.
I am not sure how to continue debugging this issue. Anyone ran into similar issues?
EDIT: Sorry, I was posting bits and pieces of different methods. Here’s the whole methods
Once you leave the
usingblock, theMemoryStreamis disposed, making yourBinaryReaderinvalid as well. Throwing away the memory stream is pulling the rug out from under your binary reader. Move all of your related reading code into a using block, if you can, and wrap yourBinaryReaderin one as well.You can read directly from the file as well, unless you have a reason to read it all in and feed it through a
MemoryStream.If the way your code is laid out keeps you from using
using, then you can keep track of theMemoryStreamandBinaryReaderobjects and implementIDisposable. Then call Dispose` on them later to clean up.The garbage collector will clean up eventually if you don’t do this, but calling
Disposeon anything that isIDisposableis good habit to get into. If you don’t, you may run into issues with open file handles or GDI objects sitting around in the finalizer queue waiting to be disposed.