尝试创建文件并立即将其删除

Kas*_*sen 8 c# file

// (1) create test file and delete it again
File.Create(Path.Combine(folder, "testfile.empty"));
File.Delete(Path.Combine(folder, "testfile.empty"));
Run Code Online (Sandbox Code Playgroud)

最后一行抛出异常:

该进程无法访问文件'\\ MYPC\C $ _AS\RSC\testfile.empty',因为它正由另一个进程使用.

这是为什么?

Mar*_*ell 21

File.Create 递给你一条小溪,你没有关闭.

using(var file = File.Create(path)) {
   // do something with it
}
File.Delete(path);
Run Code Online (Sandbox Code Playgroud)

应该管用; 或更容易:

File.WriteAllBytes(path, new byte[0]);
File.Delete(path);
Run Code Online (Sandbox Code Playgroud)

甚至只是:

using(File.Create(path)) {}
File.Delete(path);
Run Code Online (Sandbox Code Playgroud)