簡體   English   中英

C#無法訪問文件,因為它正在被另一個進程使用

[英]C# Can't Access File Because It Is Being Used By Another Process

這是我的MVC控制器,用於上傳圖片。 我正在嘗試檢查文件是否存在,然后刪除舊文件並保存新文件(如果存在)。 我在System.IO.File.Delete()處收到錯誤消息,告訴我該文件已在使用中,但是我無法弄清楚打開該文件的位置以及如何關閉它。

[HttpPost]   
public ActionResult UploadImage(int? id, HttpPostedFileBase file, EmployeeViewModel employee)
{
    Employee employeeData = db.Employees.Find(id);
    if (file != null && file.ContentLength > 0)
    {
        // Assemble File Path/Extension String
        string[] fileSplit = file.FileName.Split('.');
        string extension = fileSplit[1];
        var fileNameNew = "employeeImage-" + id + "." + extension;
        var path = Path.Combine(Server.MapPath("~/Content/employeeImages/"), fileNameNew);

        var fileExists = System.IO.File.Exists(path);

        if (fileExists)
        {
            System.IO.File.Delete(path);
            file.SaveAs(path);
        }
        else
        {
            file.SaveAs(path);
        }

    }
    return RedirectToAction("Edit", new { id = id });
}

可能存在(web)方法( 例如GET request )或其他代碼,這些圖像檢索圖像(而不是url),使該圖像作為流保持打開狀態。

最可能的答案是:

  • 該文件位於網絡共享上,並且其他人確實在使用它(它是虛擬目錄嗎?)。
  • IIS /您的Web服務器正在鎖定文件(請參閱IIS 6/7在提供圖像文件時會鎖定它們嗎?
  • 您正在上傳的文件與寫入的文件相同(如果聽起來很抱歉,請您道歉,但您需要涵蓋所有選項!)

由於我的POST請求找不到問題,因此我意識到必須在將我帶到該頁面的GET請求中。 原來我正在調用Image.FromFile(),但沒有在該GET請求中關閉它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM