【问题标题】:System.IO.MemoryStream cannot access a closed fileSystem.IO.MemoryStream 无法访问已关闭的文件
【发布时间】:2015-01-05 13:26:10
【问题描述】:

我是 Streams 的新手,我正在开发的程序需要从 hex 文件中读取数据。

文件=level.dat

我使用的代码:

    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();
        }
    }

我的程序有一个 Substrate (https://code.google.com/p/substrate-minecraft/downloads/list) 的引用,它完成了大部分工作,但它是我的代码 “无法访问已关闭的文件”

有什么帮助吗? 谢谢...

【问题讨论】:

  • 在哪里出现了这个异常?
  • @RowlandShaw nbtTree.ReadFrom(s)

标签: c# visual-studio-2012 filestream memorystream


【解决方案1】:

你的问题出在:

Stream s = fs;

fs 文件流在您的 Main 方法中关闭(using 语句处理文件流)。要解决此问题,您应该打开一个新文件流以从文件中读取:

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

【讨论】:

  • 感谢同行!这很有帮助。
【解决方案2】:

使用时

    using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
{...}

当您超出范围时,您正在关闭此文件流。所以你必须重新打开文件才能阅读

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多