Asp.net mvc 3 MVC 3进程无法访问该文件,因为另一进程正在使用该文件
我在MVC3项目中上传了一个文件Asp.net mvc 3 MVC 3进程无法访问该文件,因为另一进程正在使用该文件,asp.net-mvc-3,Asp.net Mvc 3,我在MVC3项目中上传了一个文件 [HttpPost] public ActionResult MyUpload(HttpPostedFileBase file) { string filePath = string.Empty; string path = "C:\\"; string filePath = string.Empty; try { if (file
[HttpPost]
public ActionResult MyUpload(HttpPostedFileBase file)
{
string filePath = string.Empty;
string path = "C:\\";
string filePath = string.Empty;
try
{
if (file != null && file.ContentLength > 0)
{
filePath = path + file.FileName;
file.SaveAs(filePath);
file.InputStream.Dispose();
GC.Collect();
// other operations, where can occur an exception
// (because the uploaded file can have a bad content etc.)
}
}
catch (Exception e)
{
if (file.InputStream != null)
file.InputStream.Dispose();
GC.Collect();
if (!string.IsNullOrEmpty(filePath))
{
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath); //here is the error
}
}
}
在该代码中,如果在保存文件后发生异常,我将无法删除它(也无法再次上载),因为我收到了错误
进程无法访问该文件
“[filePath]”,因为另一个进程正在使用它
那代码怎么了
编辑
我必须更改文件.InputStream.Dispose()代码>到
file.InputStream.Close();
file.InputStream.Dispose();
file.InputStream = null;
现在,它工作正常。与其在catch
块中检查file.InputStream
是否为null,不如在finally
块中处理它,如下所示:
if (file != null && file.ContentLength > 0)
{
try
{
filePath = path + file.FileName;
file.SaveAs(filePath);
// other operations, where can occur an exception
// (because the uploaded file can have a bad content etc.)
}
catch (Exception e)
{
if (!string.IsNullOrEmpty(filePath))
{
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath); //here is the error
}
}
finally
{
file.InputStream.Close();
file.InputStream.Dispose();
GC.Collect();
}
}
顺便说一下,InputStream
属性是只读属性。您不能将其设置为null。您应该在catch
块中检查file.InputStream
是否为null,而不是在finally
块中处理它,如下所示:
if (file != null && file.ContentLength > 0)
{
try
{
filePath = path + file.FileName;
file.SaveAs(filePath);
// other operations, where can occur an exception
// (because the uploaded file can have a bad content etc.)
}
catch (Exception e)
{
if (!string.IsNullOrEmpty(filePath))
{
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath); //here is the error
}
}
finally
{
file.InputStream.Close();
file.InputStream.Dispose();
GC.Collect();
}
}
顺便说一下,InputStream
属性是只读属性。您不能将其设置为null。没有名为path
的变量,但是filePath=path+file.FileName代码>,是否设置在其他地方?我已经编辑了我的问题,现在检查是否以任何方式访问该文件?请将您的编辑作为答案发布,并选择它作为答案。没有名为path
的变量,但filePath=path+file.FileName代码>,是否设置在其他地方?我已经编辑了我的问题,现在检查是否执行那些“其他操作,哪里可能发生异常”以任何方式访问该文件?请将您的编辑作为答案发布,并选择它作为答案。