无法从服务器文件夹中删除文件

Cannot delete file from server folder

我正在做一个简单的投资组合项目。我想在登录用户可以编辑的网页上显示图像。我的问题出在 [HttpPost] 编辑中,更具体地说是这部分:

if (ModelState.IsValid)
    {
      //updating current info 
      inDb = ModelFactory<ArtSCEn>.GetModel(db, artSCEn.ArtSCEnID);
      inDb.LastModified = DateTime.Now;
      inDb.TechUsed = artSCEn.TechUsed;
      inDb.DateOfCreation = artSCEn.DateOfCreation;
      inDb.Description = artSCEn.Description;
      inDb.ArtSC.LastModified = DateTime.Now;

      //validating img
      if (Validator.ValidateImage(img))
      {
           inDb.ImageString = Image.JsonSerialzeImage(img);
      }
      else
      {
          //return to the UI becuase we NEED a valid pic
           return View(artSCEn);
      }

      db.Entry(inDb).State = System.Data.Entity.EntityState.Modified;
      db.SaveChanges();

      //[PROBLEMATIC PART STARTS HERE]

      //updating the pic on the server
      //getting the string info
      string userArtImgFolder = Server.MapPath($"~/Content/Images/Artistic/{inDb.ArtSC.PersonID}");
      string imgNameOnServer = Path.Combine(
                    userArtImgFolder,
      $"{inDb.ArtSC.PersonID}_{inDb.ArtSC.ArtSCID}_{inDb.ArtSCEnID}{Path.GetExtension(img.FileName)}");


       //deleting previous pic 
       System.IO.File.Delete(imgNameOnServer);

       //creating a new pic
       Image.ResizePropotionatelyAndSave(img, Path.Combine(
                    userArtImgFolder,
                    $"{inDb.ArtSC.PersonID}_{inDb.ArtSC.ArtSCID}_{inDb.ArtSCEnID}{Path.GetExtension(img.FileName)}"));

 return RedirectToAction("Edit", "Art", new { id = inDb.ArtSCID });
            }

当我取回新图片并想删除之前的图片时,System.IO.File.Delete()总是触发无法访问资源的异常,因为其他人正在持有它。知道那可能是什么吗? 也许这很简单,我是 ASP 的新手,但就是想不通。

更新 根据评论部分的建议,我使用名为 Process Monitor 的工具检查了进程,似乎 IIS 确实锁定了资源:

顺便说一下,这个在日志中出现了 2 次。

根据操作是CreateFileMapping的事实判断,我猜它与Server.MapPath()Path.Combine()有关,但是,服务器是IDisposable (源自Controller),那么我应该处理那个吗?

此外,我要删除的资源是网站上使用的图片,这可能是个问题,但在此过程中网站的该部分未显示。

我根据@Diablo 的评论找到了解决方案。

IIS 确实保留了资源,但 Server.MapPath() 或任何该代码与它无关:它是我的页面返回数据的编辑视图。在 this SO answer 的帮助下,事实证明我粗心地使用了 BitMap,我在视图中没有使用 using 语句来获取一些图像统计信息。我用以下代码更新了辅助函数:

    public static float GetImageWidthFromPath(string imgAbsolutPath, int offset)
    {
        float width = 0;
        using (Bitmap b = new Bitmap(imgAbsolutPath))
        {
            width = b.Width - offset;
        }
        return width;
    }

现在 IIS 不保留资源,我可以删除文件。