打开文件后,我无法通过 .net core 3.1 删除文件

I can't delete file by .net core 3.1 when the file is opened

我正在尝试通过 .net core 删除文件,但是当用户打开文件时出现问题我无法删除它,即使我尝试手动删除它也是如此 Windows 显示此消息:

the action can't be completed because the file is open in IIS worker process

这是我的代码:

public async Task deleteFile(long Id)
        {
var UploadedFilesPath = Path.Combine(hosting.WebRootPath, "UploadedFiles");
   
var file = await _repository.GetAsync(Id);

 if (AbpSession.UserId == file.CreatorUserId) {
                try
                {
                    await _repository.DeleteAsync(Id);
                if (File.Exists(file.docUrl))
                {
                        // If file found, delete it   
                        var filePaht = file.docUrl;
                        await Task.Run(() => {
                            File.Delete(filePaht);
                        });

                    }
                }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.InnerException.Message.ToString());
            }
        }
            else
            {
                   
                    throw new UserFriendlyException("Error");
                    
                }
            
        }

非常natural/normal不能删除,是(正在使用中)。 (甚至 windows OS 也是这样工作的)

你可以等到关闭(可以删除)再删除。

在此区块内:

      if (File.Exists(file.docUrl))
      {
                // If file found, delete it   
                var filePaht = file.docUrl;
                await Task.Run(() => {
                    File.Delete(filePaht);
                });

       }

你应该检查它是否关闭,然后删除,像这样

      if (File.Exists(file.docUrl))
        {
                FileInfo ff = new FileInfo(file.docUrl)
                if (!ff.IsFileOpen())
                 {
                     var filePaht = file.docUrl;
                     await Task.Run(() => {
                     File.Delete(filePaht);
                     });
                 }

         }

IsFileOpen扩展方法可以放在静态class(例如FileHelpers)

public static class FileHelpers
{
    public static bool IsFileOpen(this FileInfo f)
    {
        FileStream stream = null;

        try
        {
            stream = f.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            return true;
        }
        finally
        {
            if (stream != null) stream.Close();
        }

        return false;
    }
}