我是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)的引用,它完成了大部分工作,但是我的代码给出了 “无法访问已关闭的文件”
有任何帮助吗? 感谢...
答案 0 :(得分:2)
您的问题出在:
Stream s = fs;
fs文件流在Main方法中关闭(using语句处理文件流)。要解决此问题,您应该打开一个新的文件流来从文件中读取:
Stream s = new FileStream("PCWorld\\level.dat", FileMode.Read);
答案 1 :(得分:0)
使用时
using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
{...}
当你走出范围时,你正在关闭这个文件流。所以你必须重新打开文件才能阅读