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がブロック内で null でないかどうかを確認する代わりに、次のようにブロック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 に答える