[英]Trying to create a file and delete it immediately
// (1) create test file and delete it again
File.Create(Path.Combine(folder, "testfile.empty"));
File.Delete(Path.Combine(folder, "testfile.empty"));
最后一行拋出異常:
該進程無法訪問文件'\\\\ MYPC \\ C $ _AS \\ RSC \\ testfile.empty',因為它正由另一個進程使用。
這是為什么?
File.Create
你回流,你還沒有關閉。
using(var file = File.Create(path)) {
// do something with it
}
File.Delete(path);
應該管用; 或更容易:
File.WriteAllBytes(path, new byte[0]);
File.Delete(path);
甚至只是:
using(File.Create(path)) {}
File.Delete(path);
當你創建文件時,你正在使用它,直到你關閉它 - 你還沒有這樣做,因此錯誤。
要關閉文件,您應該將創建包裝在using
語句中:
using(var file = File.Create(Path.Combine(folder, "testfile.empty")))
{
}
File.Delete(Path.Combine(folder, "testfile.empty"));
試試..
File.Create(Path.Combine(folder, "testfile.empty")).Dispose();
File.Delete(Path.Combine(folder, "testfile.empty"));
Create
方法返回一個必須在進行其他操作之前關閉的文件流:
FileStream fs=File.Create( "testfile.empty");
fs.Close();
File.Delete("testfile.empty");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.