c# - "File in use"写入文本文件时出错

标签 c# .net winforms file save

我收到错误 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);
            }
        }

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

最佳答案

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

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

关于c# - "File in use"写入文本文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19641424/

相关文章:

c# - 与连接(桥接)表的一对多关系

c# - 调用Windows API时CLR怎么比我快

c# - '无法建立连接,因为目标机器主动拒绝它

c# - 关闭另一个窗口时如何从一个窗口更新组合框?

c# - VC# 窗体闪烁

C#:在对象之间创建强引用,而无需一个引用另一个

c# - 将图像保存在sql数据库中C#

c# - 计算十亿元素列表中唯一元素的最快方法是什么?

.net - 使用 Windbg SOS 扩展单步执行源代码

c# - SetParent Hook ,如何解钩?