2015-01-05 123 views
-4

我是Streams新手,在開發程序時需要從hex文件讀取數據。使用System.IO.MemoryStream無法訪問已關閉的文件

文件= level.dat

代碼IM:

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

我的程序具有底物(https://code.google.com/p/substrate-minecraft/downloads/list)的參考,並且確實大部分的工作,但其代碼 「不能訪問一個封閉的文件」

有什麼幫助嗎? 謝謝...

+0

*,其中*是否與該異常失敗? –

+0

@RowlandShaw'nbtTree.ReadFrom(s)' – DMP9

回答

2

你的問題是:

Stream s = fs; 

FS的FILESTREAM是你的主要方法關閉(using語句部署的FILESTREAM)。爲了解決這個問題,你應該打開一個新的FILESTREAM從文件中讀取:

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

感謝同行!這有很大幫助。 – DMP9

相關問題