我正在尝试管理我的网络应用程序中的文件。有时,我必须在文件夹中创建一个文件(使用 File.Copy):
File.Copy(@oldPath, @newPath);
几秒钟后该文件可能会被删除:
if (File.Exists(@newPath)) {
File.Delete(@newPath);
}
但是,我不知道为什么在 File.Copy 之后新文件仍然被服务器进程(IIS、w3wp.exe)阻止。在 File.Delete 之后我得到异常:
“该进程无法访问该文件,因为该文件正在被使用
另一个过程。”
根据 Api,File.Copy 不会阻止文件,不是吗?
我尝试过释放资源,但没有成功。我该如何解决这个问题?
UPDATED:事实上,使用 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();
}
}