【问题标题】:Saving file: The process cannot access the file because it is being used by another process [duplicate]保存文件:该进程无法访问该文件,因为它正在被另一个进程使用[重复]
【发布时间】:2013-07-13 20:56:19
【问题描述】:

我正在使用 VS2012 和 Windows 8 创建一个简单的 Windows 应用程序。 有一个富文本框,用户应该在其中输入文本,当表单关闭时,它应该将富文本框的文本保存在一个文件中。但是,几乎总是应用程序抛出错误,指出“该进程无法访问该文件,因为它正被另一个进程使用” 代码如下

 public Form1()
    {
        InitializeComponent();

        try
        {
            richTextBox1.LoadFile("D:\\MyNotes\\MyNotes.rtf");
        }
        catch (Exception ex)
        {

            System.IO.File.Create("D:\\MyNotes\\MyNotes.rtf");
        }
    }
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {


        try
        {

            System.IO.StreamWriter SW = new System.IO.StreamWriter(
            "D:\\MyNotes\\MyNotes.rtf", false, Encoding.ASCII);
            SW.Write(richTextBox1.Text);
            SW.Close();

                            //Even this does not work
            // richTextBox1.SaveFile("D:\\MyNotes\\MyNotes.rtf");


        }
        catch (Exception ex)
        {


            MessageBox.Show(ex.Message);

        }
    }

【问题讨论】:

  • @CodeCaster True,但此处提供了确切答案。关于为什么它真的是这样的细节,在这里。所以我认为这是更好地理解和实施
  • 当您的问题被近距离投票为重复时,这意味着您的问题的原则已经在本网站的其他地方得到回答,即在您的问题中标记为重复。虽然环境可能因问题而异,但您并不是唯一一个致电File.Create() 并忘记关闭返回的句柄的人。
  • 那么我应该删除这个问题吗?
  • 不,只是等待它关闭。您的措辞或答案的措辞可能会帮助未来通过搜索到达这里的访问者。 :-)

标签: c#


【解决方案1】:

如果您查看 MSDN,您会看到 File.Create method returns a FileStream

在您的try..catch 中,您正在使用File.Create 创建一个文件,但将FileStream 挂起。

把它改成这样:

if (!File.Exists("D:\\MyNotes\\MyNotes.rtf")) {
    using (var stream = File.Create("D:\\MyNotes\\MyNotes.rtf")) {
        // nop
    }
}

.. 或致电Close()

这解释了“几乎总是”.. 因为当你再次运行它时,文件被创建并且块不运行。

您可以考虑根本不创建文件。

【讨论】:

    【解决方案2】:
    FileStream fs = System.IO.File.Create("D:\\MyNotes\\MyNotes.rtf");
    fs.Close();
    

    System.IO.File.Create() 一直打开您的文件。

    【讨论】:

      【解决方案3】:

      File.Create Method 返回一个Stream(更具体地说是一个FileStream,并且该类型实现IDisposable。每当您获得 IDisposable 时,适当地处置它是很重要的。因为您不处置File.Create 返回的对象,你会得到异常。

      通常在读取/写入文件时,您可以使用 File.ReadAllTextFile.WriteAllText 方法实现您想要的,因为它们不返回 IDisposable 对象,因此在这方面更容易使用。

      在您的情况下,我认为没有理由使用返回 IDisposable 对象的方法,只需使用 File.ReadAllText 和 File.WriteAllText。以另一种方式解释:您不需要流,您只是想读/写文本。

      其实你甚至不需要 File.ReadAllText:

      public class Form1
      {
          private const string fileName = @"D:\MyNotes\MyNotes.rtf";
      
          public Form1()
          {
              InitializeComponent();
      
              if (!File.Exists(fileName))
                  File.WriteAllText(fileName, "");
      
              richTextBox1.LoadFile(fileName);
          }
      
          private void Form1_FormClosing(object sender, FormClosingEventArgs e)
          {
              richTextBox1.SaveFile(fileName);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-10
        相关资源
        最近更新 更多