我收到错误 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/