文件输入/输出问题

时间:2013-07-19 07:59:23

标签: c# file file-io

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 个答案:

答案 0 :(得分: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());
        }
    }
}

答案 1 :(得分: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());
}

答案 2 :(得分: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());
    }
}

使用'使用'是很好的做法。

答案 3 :(得分:0)

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

我假设您要保存更改,因此请使用Flush保存或使用Close with AutoFlush代替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();                
          }
        }
      }