2

我在我的 MVC 3 项目中上传了一个文件。

    [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]”,因为它正被另一个进程使用。

该代码有什么问题?

编辑

我不得不file.InputStream.Dispose();改变

file.InputStream.Close(); 
file.InputStream.Dispose(); 
file.InputStream = null; 

而且,现在它工作正常。

4

1 回答 1

0

而不是检查块file.InputStream内是否不为空catch,您应该将其放置在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。

于 2015-01-28T16:40:30.650 回答