英文:
Creating XML file if not exists throwing error
问题
我正在尝试创建一个XML文件,如果它不存在:
// 检查xml文件是否存在。如果不存在,则创建
if (!File.Exists(Globals.baseDir + @"emp.xml"))
{
File.AppendText(Globals.baseDir + @"emp.xml");
//也尝试过File.Create, File.CreateText
}
它确实创建了文件。然而,稍后当程序向其写入时,会抛出一个异常:
> System.IO.IOException: 由于另一个进程正在使用文件“C:\...\emp.xml”,因此无法访问该过程。
如果我第二次运行程序,它会使用相同的文件,并且可以完美地进行处理。我还尝试使用File.Create和File.CreateText,但都产生相同的结果。
英文:
I'm trying to create an XML file if it does not exist:
// check if xml file exists. If not, then create
if (!File.Exists(Globals.baseDir + @"emp.xml"))
{
File.AppendText(Globals.baseDir + @"emp.xml");
//Also tried File.Create, File.CreateText
}
It does create the file. However, later when the program writes to it, then it throws an exception:
> System.IO.IOException: The process cannot access the file 'C:...\emp.xml' because it is being used by another process.
If I run the program a second time, it uses the same file and does the processing perfectly. I also tried using File.Create
and File.CreateText
, but all produce the same result.
答案1
得分: 2
File.AppendText
创建一个StreamWriter
- 然后你没有释放它,所以底层的句柄仍然保持打开状态。
如果你只是想创建一个空文件,我会建议使用File.WriteAllBytes(path, new byte[0])
- 这样就没有需要释放的东西了。或者你可以使用:
using var stream = File.Create(path);
...然后让它自己进行释放...
英文:
File.AppendText
creates a StreamWriter
- which you're then not disposing, so the underlying handle is still open.
If you just want to create an empty file, I'd just use File.WriteAllBytes(path, new byte[0])
- that way there's nothing to dispose. Or you could use
using var stream = File.Create(path);
... and then let it dispose of itself...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论