【问题标题】:Cannot delete file because it is being used by another process, ASP.NET Core MVC无法删除文件,因为它正被另一个进程 ASP.NET Core MVC 使用
【发布时间】:2019-05-24 09:50:35
【问题描述】:

我正在使用带有 MVC 的 ASP.Net Core 来创建应用程序。我目前正在使用 Visual Studio 和 IIS Express。 以下是我目前的项目结构:

*项目目录

-wwwroot

-区域

-附件

-控制器

-模型

-观看次数

我目前将图像存储在附件文件夹中。

以前我在我的 startup.cs 中写过类似的东西

app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(
        Path.Combine(Directory.GetCurrentDirectory(), "Attachments")),
            RequestPath = "/Attachments"
        });

下面我也做过类似的事情:

appendImage(@Url.Content("~/Attachments/")+result.fileName);

我这样做是为了在我的视图上显示图像。图片显示成功。

我现在想要实现的是在 UI 上允许用户选择删除该附件文件夹中的文件

我尝试了以下代码:

string contentRootPath = _hostingEnvironment.ContentRootPath;
string fullImagePath = Path.Combine(contentRootPath +   "\\Attachments", currentItemToDelete.FileName);

if (System.IO.File.Exists(fullImagePath))
{
  try{
       System.IO.File.Delete(fullImagePath);
  }catch(Exception e){
       operationResult = "Attachment Path. Internal Server Error";
  }
}

执行确实进入if (System.IO.File.Exists(fullImagePath)) 但是当它到达System.IO.File.Delete 时会引发异常。异常表明驻留在该路径中的文件正被另一个进程使用。因此我无法删除该文件。访问该文件的唯一进程是我同时创建/调试的 Web 应用程序。如何防止发生此异常?我必须使用其他类型的代码来删除文件吗?

编辑以包含更多详细信息:

在我的视野中(index.cshtml):

appendImage 是一个 javascript 函数:

function appendImage(imgSrc) {
        var imgElement = document.createElement("img");
        imgElement.setAttribute('src', imgSrc);


        if (imgSrc.includes(null)) {
            imgElement.setAttribute('alt', '');
        }
        imgElement.setAttribute('id', "img-id");

        var imgdiv = document.getElementById("div-for-image");
        imgdiv.appendChild(imgElement);
}

该函数在下面调用:

$.ajax({
                url:'@Url.Action("GetDataForOneItem", "Item")',
                type: "GET",
                data: { id: rowData.id },
                success: function (result) {
                    removeImage();
                    appendImage(@Url.Content("~/Attachments/")+result.fileName);
                    $("#edit-btn").attr("href", '/Item/EditItem?id=' + result.id);
                },
                error: function (xhr, status, error) {

                }
        });

调用appendImage()后;我更改了<a> 标签的href。当用户点击链接时,用户会被定向到另一个页面(edit.cshtml)。在页面中,位于该路径中的图像也显示为如下代码:

<img src="@Url.Content("~/Attachments/"+Model.FileName)" alt="item image" />

在这个新页面(edit.cshtml)中,有一个删除按钮。单击删除按钮后,程序的执行将转到该控制器功能的控制器:

[HttpPost]
public string DeleteOneItem(int id)
{
        //query the database to check if there is image for this item.
        var currentItemToDelete = GetItemFromDBDateFormatted(id);
        if (!string.IsNullOrEmpty(currentItemToDelete.FileName))
        {
            //delete the image from disk. 
            string contentRootPath = _hostingEnvironment.ContentRootPath;
            string fullImagePath = Path.Combine(contentRootPath + "\\Attachments", currentItemToDelete.FileName);

            if (System.IO.File.Exists(fullImagePath))
            {
                try
                {
                    System.IO.File.Delete(fullImagePath);
                }catch(Exception e)
                {

                }
            }

        }

        return "";

 }

编辑回答问题:

添加

System.GC.Collect(); 
System.GC.WaitForPendingFinalizers(); 

system.io.file.delete 之前

【问题讨论】:

  • 您要删除的图像是否也在代码中显示(使用)?如果是这样,我猜你需要从任何使用它的对象中“释放”这个文件,然后才能删除它。 appendImage(@Url.Content("~/Attachments/")+result.fileName); … 行似乎正在“使用”该文件。
  • @JohnG,那段代码 appendImage();在我的视图(.cshtml)中调用。删除文件的代码(system.io.file.delete)驻留在控制器中。如何释放文件?在调用 system.io.file.delete 之前,我必须在控制器中编写一些其他代码吗?
  • 这取决于 appendImage() 正在做什么。你能分享一下appendImage()里面的相关代码吗?可能有一些文件 I/O 逻辑在需要时没有释放/关闭/释放流。
  • @AashishKoirala,我编辑了问题以包含更多细节。

标签: javascript c# html asp.net asp.net-core


【解决方案1】:

您可以用这个给定的代码替换您的 C# 方法 DeleteOneItem。也许它可能会起作用。

[HttpPost]
public string DeleteOneItem(int id)
{
    //query the database to check if there is image for this item.
    var currentItemToDelete = GetItemFromDBDateFormatted(id);
    if (!string.IsNullOrEmpty(currentItemToDelete.FileName))
    {
        //delete the image from disk. 
        string contentRootPath = _hostingEnvironment.ContentRootPath;
        string fullImagePath = Path.Combine(contentRootPath + "\\Attachments", currentItemToDelete.FileName);

        if (System.IO.File.Exists(fullImagePath))
        {
            try
            {
                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
                System.IO.File.Delete(fullImagePath);

            }
            catch (Exception e) { }
        }
    }
    return "";
}

【讨论】:

    【解决方案2】:
    try
    {
     System.GC.Collect(); 
     System.GC.WaitForPendingFinalizers(); 
     System.IO.File.Delete(fullImagePath);
    }
    catch(Exception e){
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-04
      • 2014-05-26
      • 1970-01-01
      • 2016-09-21
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多