Search code examples
c#visual-studio-2012filestreammemorystream

System.IO.MemoryStream cannot access a closed file


I'm new to Streams and in the program i'm developing requires reading data from a hex file.

File=level.dat

The code im using:

    FileStream fs;
    private void Form1_Load(object sender, EventArgs e)
    {
        Main("PCWorld\\level.dat");
        NbtTree nbtTree = new NbtTree();
        Stream s = fs;
        Stream destStream = new MemoryStream();
        nbtTree.ReadFrom(s);
        nbtTree.WriteTo(destStream);
    }

void Main():

void Main(string filename)
    {
        // From MSDN Forums, slightly modified by me
        try
        {
            string fileName = filename;

            // Create random data to write to the file. 
            byte[] dataArray = new byte[100000];
            new Random().NextBytes(dataArray);

            using (FileStream
                fileStream = new FileStream(fileName, FileMode.Create))
            {
                // Write the data to the file, byte by byte. 
                for (int i = 0; i < dataArray.Length; i++)
                {
                    fileStream.WriteByte(dataArray[i]);
                }

                // Set the stream position to the beginning of the file.
                fileStream.Seek(0, SeekOrigin.Begin);

                // Read and verify the data. 
                for (int i = 0; i < fileStream.Length; i++)
                {
                    if (dataArray[i] != fileStream.ReadByte())
                    {
                        MessageBox.Show("Failed to load " + fileName + " (MCPC.dll)\n\nReason: Failed to read bytes\nResult: Close();\nSoloution: Try again and/or tell DMP9 Software", "Error");
                        Close();
                        return;
                    }
                    fs = fileStream;
                }
            }
        }
        catch (OutOfMemoryException ex)
        {
            MessageBox.Show("Failed to load NBT++.PC.exe\n\nReason: Out of memory (System.OutOfMemoryException: " + ex.Message + ")\nResult: Close();\nSoloution: Your PC Does not have enough RAM to run NBT++", "Error");
            Close();
        }
    }

My program has a reference of Substrate (https://code.google.com/p/substrate-minecraft/downloads/list) and that does most of the work, but its my code giving the "Cannot access a closed file"

Any help? Thanks...


Solution

  • Your problem is in:

    Stream s = fs;
    

    The fs filestream is closed in your Main method (using statement disposes the filestream). To fix this you should open a new filestream to read from the file:

    Stream s = new FileStream("PCWorld\\level.dat", FileMode.Read);