首页 > 解决方案 > 无法删除文件,因为它正被另一个进程 ASP.NET Core MVC 使用

问题描述

我正在使用带有 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 之前

标签: javascriptc#htmlasp.netasp.net-core

解决方案


你可以用这个给定的代码替换你的 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 "";
}

推荐阅读