後文件正在被另一個進程使用我正在嘗試管理我的Web應用程序中的文件。有時候,我必須創建一個文件夾(與File.Copy)在文件中:File.Copy
File.Copy(@oldPath, @newPath);
,幾秒鐘後該文件可能會被刪除:
if (File.Exists(@newPath)) {
File.Delete(@newPath);
}
不過,我不知道爲什麼在File.Copy之後,新文件仍然被服務器進程(IIS,w3wp.exe)阻止。 File.Delete後,我得到異常:
「因爲它正由 另一個進程的進程無法訪問該文件。」
根據Api,File.Copy不會阻止文件,是嗎?
我試圖釋放資源,但它沒有奏效。我該如何解決這個問題?
更新:事實上,使用Process Explorer文件被IIS進程阻止。我試圖實現複製代碼,以手動釋放資源,但問題仍然繼續:
public void copy(String oldPath, String newPath)
{
FileStream input = null;
FileStream output = null;
try
{
input = new FileStream(oldPath, FileMode.Open);
output = new FileStream(newPath, FileMode.Create, FileAccess.ReadWrite);
byte[] buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
catch (Exception e)
{
}
finally
{
input.Close();
input.Dispose();
output.Close();
output.Dispose();
}
}
那麼什麼是使用該文件?很明顯,你不會毫無意義地創建一個文件,只有在幾秒鐘後才刪除它,所以一定要使用它。那是什麼? –
該文件來自另一個系統,所以它被更改,我必須更換舊的。我正在開發一個「鏡像」系統。 – jbernal
也許這個類似的問題可能會幫助你:http://stackoverflow.com/questions/7937966/ – Bridge