2011-03-15 39 views
5
// (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「因爲它正被另一個 進程使用。

這是爲什麼?

回答

18

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); 
3

當您創建的文件,直到你關閉你正在使用它 - 你還沒有這樣做,因此錯誤。

爲了關閉文件,你應該換建立在using聲明:

using(var file = File.Create(Path.Combine(folder, "testfile.empty"))) 
{ 
} 
File.Delete(Path.Combine(folder, "testfile.empty")); 
1

嘗試..

File.Create(Path.Combine(folder, "testfile.empty")).Dispose(); 
File.Delete(Path.Combine(folder, "testfile.empty")); 
1

Create方法返回一個必須做之前接近一個FILESTREAM其他操作:

FileStream fs=File.Create("testfile.empty"); 
fs.Close(); 
File.Delete("testfile.empty"); 
相關問題