0
int AccNum;
FileStream myfile = new FileStream("C:\\bankin.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamReader rd = new StreamReader(myfile);
StreamWriter wt = new StreamWriter(myfile);
int a = Convert.ToInt32(rd.ReadLine());
AccNum = a;
a += 1;
wt.WriteLine(Convert.ToString(a));
Console.WriteLine(rd.ReadLine());
rd.Close(); 
wt.Close();
myfile.Close();

我正在尝试增加文件banking.txt 中的整数值,但出现以下错误:

无法访问已关闭的文件

4

4 回答 4

1

也许是因为你rd之前关门了wt

如果是这种情况,我建议使用该using语句来防止将来出现这种混淆:

int AccNum;
using (FileStream myfile = new FileStream("C:\\bankin.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
    using (StreamReader rd = new StreamReader(myfile)) {
        using (StreamWriter wt = new StreamWriter(myfile)) {
            int a = Convert.ToInt32(rd.ReadLine());
            AccNum = a;
            a += 1;
            wt.WriteLine(Convert.ToString(a));
            Console.WriteLine(rd.ReadLine());
        }
    }
}
于 2013-07-19T08:01:16.263 回答
1

更改代码以使用using语句

提供一种方便的语法,确保正确使用 IDisposable 对象。

int AccNum;
using(FileStream myfile = new FileStream("C:\\bankin.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
using(StreamReader rd = new StreamReader(myfile))
using (StreamWriter wt = new StreamWriter(myfile))
{
    int a = Convert.ToInt32(rd.ReadLine());
    AccNum = a;
    a += 1;
    wt.WriteLine(Convert.ToString(a));
    Console.WriteLine(rd.ReadLine());
}
于 2013-07-19T08:04:56.927 回答
0
int AccNum;
using(FileStream myfile = new FileStream("C:\\bankin.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
    using(StreamReader rd = new StreamReader(myfile))
    {
        using(StreamWriter wt = new StreamWriter(myfile))
        {
            int a = Convert.ToInt32(rd.ReadLine());
            AccNum = a;
            a += 1;
            wt.WriteLine(Convert.ToString(a));
        }
        Console.WriteLine(rd.ReadLine());
    }
}

使用“使用”是一个好习惯。

于 2013-07-19T08:07:29.750 回答
0

异常是由 wt.Close() 行产生的,因为文件已经关闭。StreamReader 上的 Close 方法关闭流和所有底层资源(参见http://msdn.microsoft.com/en-us/library/system.io.streamreader.close.aspx

我假设您要保存更改,因此请使用 Flush 保存或使用带有 AutoFlush 的 Close 代替 Flush。这是您的示例,经过一些修改

int AccNum;
      using (FileStream myfile = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
      {
        using (StreamReader rd = new StreamReader(myfile))
        {
          using (StreamWriter wt = new StreamWriter(myfile))
          {             
            int a = Convert.ToInt32(rd.ReadLine());
            AccNum = a;
            a += 1;
            wt.WriteLine(Convert.ToString(a));
            Console.WriteLine(rd.ReadLine());
            wt.Flush();                
          }
        }
      }
于 2013-07-19T08:20:46.640 回答