读取时报错,“无法访问已关闭的文件”

fishoffly 2011-08-15 08:28:24
private void button2_Click(object sender, EventArgs e)
{
string fileName = "MyNew.data";
if (!(File.Exists(fileName)))
{
MessageBox.Show("当前文件不存在");
return;
}
string strData = "";
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fs);
strData = reader.ReadString();
for (int i = 0; i < 200;i++ )
{
if (i == 0)
{
strData += reader.ReadUInt32().ToString();

}
else
{
strData += "||" + reader.ReadUInt32().ToString();
}
textBox2.Text = strData;
fs.Close();
reader.Close();
}
}


标红部分报的错“无访问已关闭的文件”,但是前面fs已经是打开模式了啊?谢谢各位大侠。谢谢
...全文
1052 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
imaginecaosen 2011-08-18
  • 打赏
  • 举报
回复
解决了, breader.Close();//在前面
fstream.Close();

fishoffly 2011-08-15
  • 打赏
  • 举报
回复
凌晨5点写的,加班久了。迷迷糊糊的。哈哈哈,低级错误。
fishoffly 2011-08-15
  • 打赏
  • 举报
回复
呵呵呵,忘了括号了。谢了
dai78 2011-08-15
  • 打赏
  • 举报
回复
呵呵!这代码写的
huangwenquan123 2011-08-15
  • 打赏
  • 举报
回复
[Quote=引用楼主 fishoffly 的回复:]
标红部分报的错“无访问已关闭的文件”,但是前面fs已经是打开模式了啊?谢谢各位大侠。谢谢
[/Quote]不是在i==0的时候抱错的,而是在else中,说明第一次连接,第二次被你关闭了。
dalmeeme 2011-08-15
  • 打赏
  • 举报
回复

fs.Close();
reader.Close();
移到循环外啊,否则循环一次就关闭了。
imaginecaosen 2011-08-15
  • 打赏
  • 举报
回复
我在关闭文件后又定义了一个新的FileStream对象来读取文件,为什么还是提示“无法访问关闭的文件”?

namespace BinaryFileTest
{
class Program
{
static void Main(string[] args)
{
string filepath = @"D:\Test13.001";
if(!File.Exists(filepath))
{
Console.WriteLine("file not exist!");
return;
}
FileStream fstream=new FileStream (filepath ,FileMode.Open,FileAccess.Read);
BinaryReader breader=new BinaryReader (fstream);
Console.WriteLine("filelength" + fstream.Length.ToString()+"bytes");
string outstr;//用于输出的字符串
outstr=breader.ReadInt16().ToString ();
Console.WriteLine("[1] HEDER VERSION: "+outstr);
fstream.Close();
breader.Close();

//重新定义
FileStream fstream2 = new FileStream(filepath, FileMode.Open, FileAccess.Read);
BinaryReader breader2 = new BinaryReader(fstream2,Encoding.Default);
breader2.BaseStream.Position = 58;
char[] cc = new char[8];
for (int i = 0; i < 8; i++)
cc[i] = breader.ReadChar();
Console.WriteLine(cc);
fstream2.Close();
breader2.Close();
}
}
}
谁能帮我分析分析??

111,096

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧