【问题标题】:"File in use" error when writing to text file写入文本文件时出现“文件正在使用”错误
【发布时间】:2013-10-28 17:37:49
【问题描述】:

当我尝试创建一个文件然后写入它时,我收到了错误The process cannot access the file 'C:\Users\Ryan\Desktop\New folder\POSData.txt' because it is being used by another process.。什么进程正在使用该文件?创建文件后,我检查了要调用的 file.close,但它不存在。我该如何度过这个难关?谢谢!

这是我的代码:

MessageBox.Show("Please select a folder to save your database to.");
        this.folderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.Desktop;
        DialogResult result = this.folderBrowserDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            databasePath = folderBrowserDialog1.SelectedPath;
            if (!File.Exists(databasePath + "\\POSData.txt"))
            {
                File.Create(databasePath + "\\POSData.txt");
            }

            using (StreamWriter w = new StreamWriter(databasePath + "\\POSData.txt", false))
            {
                w.WriteLine(stockCount);
            }
        }

编辑:仅在创建文件时发生。如果已经存在,则不会发生错误。

【问题讨论】:

标签: c# .net winforms file save


【解决方案1】:

实际上,甚至不用费心使用File.Create。您收到该错误的原因是 File.Create 正在该文本文件上打开一个流。

string filePath = "databasePath + "\\POSData.txt"";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
    //write to the file
}

【讨论】:

  • @Nathan 乐于助人。
【解决方案2】:

当您调用 File.Create 时,您保持文件打开(即您永远不会关闭文件)。

StreamWriter 会在文件不存在时为您创建文件,所以我不会费心检查自己。您可以删除检查它是否存在的代码,如果不存在则创建它。

if (result == DialogResult.OK)
{
    databasePath = folderBrowserDialog1.SelectedPath;

    using (StreamWriter w = new StreamWriter(databasePath + "\\POSData.txt", false))
    {
        w.WriteLine(stockCount);
    }
 }

注意,如果文件不存在,StreamWriter 构造函数中的第二个bool 参数将被忽略。

【讨论】:

    【解决方案3】:

    File.Create 还会打开文件进行读/写。因此,您在 File.Create 时会留下一个打开的 FileStream。

    假设覆盖是可以的,那么你可能想要做这样的事情:

            using (var fs = File.Create(databasePath + "\\POSData.txt"))
            using (StreamWriter w = new StreamWriter(fs))
            {
                w.WriteLine(stockCount);
            }
    

    鉴于 File.Create:

    创建或覆盖指定路径中的文件。

    【讨论】:

      【解决方案4】:

      File.Create 返回一个可能需要关闭的FileStream 对象。

      此方法创建的 FileStream 对象有一个默认的 FileShare 无值;没有其他进程或代码可以访问创建的文件 直到原始文件句柄被关闭。

              using (FileStream fs = File.Create(databasePath + "\\POSData.txt"))
              {
                   fs.Write(uniEncoding.GetBytes(stockCount), 0, uniEncoding.GetByteCount(stockCount));
              }
      

      【讨论】:

        【解决方案5】:

        我用过,效果很好

        `File.AppendAllText(fileName,"");`
        

        这会创建一个新文件,不向其中写入任何内容,然后为您关闭它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-03
          • 2018-02-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多