【问题标题】:Error message 'Can't write to textfile: File is being used by another process'错误消息“无法写入文本文件:文件正被另一个进程使用”
【发布时间】:2013-07-26 15:17:45
【问题描述】:

我的 C# 表单有一个问题。我有一个文本框,用于在单击外部 txt 文件的按钮时添加内容,以及一个显示 txt 文件内容的组合框。

我的代码:

String PathFile = @"Mypath";

private void button1_Click(object sender, EventArgs e)
{
    StreamWriter sw = new StreamWriter(PathFile);
    sw.WriteLine(textBox1.Text);
    sw.Close();
}

private void Form1_Load(object sender, EventArgs e)
{
    try
    {

        StreamReader sr = new StreamReader(PathFile);
        string line = sr.ReadLine();
        while (line != null)
        {
            comboBox1.Items.Add(line);
            line = sr.ReadLine();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error : " + ex.Message);
    }
}

组合框效果很好并显示内容,但是当我尝试使用文本框添加新条目时,结果如下。

system.io.ioexception 进程无法访问该文件,因为它正被另一个进程使用

我了解文件被组合框的进程锁定,但我该怎么做才能解决这种情况?

【问题讨论】:

  • 好吧,它在第一行就删掉了,对不起,大家好!

标签: c# visual-studio file


【解决方案1】:

您不会在表单加载期间处理 StreamReader。

using(StreamReader sr = new StreamReader(PathFile))
{
    string line = sr.ReadLine();
    while (line != null)
    {
        comboBox1.Items.Add(line);
        line = sr.ReadLine();
    }
}

另外,当您使用StreamWriter 将数据写入文件时,您还需要处理流:

using(StreamWriter sw = new StreamWriter(PathFile))
{ 
    sw.WriteLine(textBox1.Text);
}

那么using 做了什么?这是一个相当整洁的结构。它接受IDisposable 并确保无论代码到达using 块的末尾还是抛出异常,对象都会被释放。我们需要处理流之类的东西,因为它们拥有非托管资源(例如文件句柄),我们不想等待垃圾收集器启动并实际释放句柄。

using 在语义上等价于:

IDisposable someObjectThatIsDispoable; // e.g. StreamWriter/StreamReader, et al
try
{
     // your code here
}
finally
{
    if(someObjectThatIsDisposable != null)
        someObjectThatIsDisposable.Dispose();
}

此外, dispose 负责关闭文件,因此无需调用 Close(因此已将其从该答案中删除)。

【讨论】:

  • "Also, when you're writing, do this - it also needs disposing."你能解释一下吗?
  • 这篇文章给出了一个正确的答案,但可以使用更多的解释来解释 using 的确切用途,以及它是如何工作的。
【解决方案2】:

打开/关闭 Stream 的正确方法是通过using statement。

在您的 Form_Load 中

 using(StreamReader sr = new StreamReader(PathFile))
 {
    string line = sr.ReadLine();
    while (line != null)
    {
        comboBox1.Items.Add(line);
        line = sr.ReadLine();
    }
 }

这将确保 StreamReader 在右大括号处的正确关闭和处理,即使在 using 块内出现异常的情况下也

当然,您也应该以同样的方式更改 Button_Click 代码

private void button1_Click(object sender, EventArgs e)
{
    using(StreamWriter sw = new StreamWriter(PathFile))
    {
         sw.WriteLine(textBox1.Text);
    }
    // No really needed to call close
}

【讨论】:

    【解决方案3】:

    正如其他答案中所述,您收到该错误是因为您的流没有被关闭。但是,您可以避免显式使用StreamReader,也可以改用File.ReadAllLines 来缩短代码。

    try
    {
        foreach(string line in File.ReadAllLines(PathFile))
        {
           comboBox1.Items.Add(line);           
        }
    
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error : " + ex.Message);
    }
    

    虽然不一定,但在处理实现IDisposable 的类时,使用using 块通常是个好主意。所以对于你的StreamWriter,你可以使用这个

    using(StreamWriter sw = new StreamWriter(PathFile))
    {
       sw.WriteLine(textBox1.Text);
    }
    

    这可确保关闭流并释放 StreamWriter 对象。

    【讨论】:

      【解决方案4】:

      在加载方法的StreamWriter上调用dispose释放文件。

      private void Form1_Load(object sender, EventArgs e)
      {
          StreamReader sr = new StreamReader(PathFile);
          try
          {
              string line = sr.ReadLine();
              while (line != null)
              {
                  comboBox1.Items.Add(line);
                  line = sr.ReadLine();
              }
              sr.Dispose();
              sr = null; 
          }
          catch (Exception ex)
          {
              MessageBox.Show("Error : " + ex.Message);
          }
          finally //Just in case any exception is thrown.
          {
             if (sr != null)
                 sr.Dispose();
                 sr = null;
          }
      }
      

      【讨论】:

      • using 的重点在于它会释放对象,即使抛出异常也会使这个解决方案变得非常冗长,恕我直言。 :)
      • @Moo-Juice:是的,我知道你在说什么,但我要向 OP 说明一点,以便他/她明白还有另一种方法。
      • Why not just wrap that code around a using 并且您不必显式调用Dispose()?
      【解决方案5】:

      您没有处置StreamReader。试试这个:

      private void Form1_Load(object sender, EventArgs e)
      {
          StreamReader sr = null; // declare the StreamReader outside the try-catch-finally block
          try
          {
      
              sr = new StreamReader(PathFile);
              string line = sr.ReadLine();
              while (line != null)
              {
                  comboBox1.Items.Add(line);
                  line = sr.ReadLine();
              }
      
          }
          catch (Exception ex)
          {
              MessageBox.Show("Error : " + ex.Message);
          }
          finally
          {
              if (sr != null)
              {
                   sr.Dispose(); // dispose the StreamReader if it's not null
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-26
        • 1970-01-01
        • 2011-04-13
        相关资源
        最近更新 更多