无法从服务器文件夹

时间:2018-02-08 19:47:04

标签: c# asp.net-mvc system.io.file

我正在从事一个简单的投资组合项目。我想在登录用户可以编辑的网页上显示图像。我的问题出在[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确实锁定了资源: Resource enter image description here

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

根据操作CreateFileMapping这一事实来判断,我认为它与Server.MapPath()Path.Combine()有关,但是,服务器是IDisposable(正在派生自Controller),那么我应该处理的是什么?

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

1 个答案:

答案 0 :(得分:1)

我发现解决方案建立在@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没有保留资源,我可以删除该文件。