我正在尝试管理我的 Web 应用程序中的文件。有时,我必须在文件夹中创建一个文件(使用 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();
}
}