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



我正试图通过.net core删除一个文件,但当用户打开文件时出现问题,我无法删除它,即使我试图手动删除它,Windows也会向我显示以下消息:

由于文件在IIS工作进程中打开,因此无法完成该操作处理

这是我的代码:

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");

}

}

不能删除是非常自然/正常的,它是(在使用中(。(即使是windows操作系统也是如此(

您可以等到它关闭(可以删除(,然后再删除。

在这个区块内:

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扩展方法可以放在静态类(例如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;
}
}

最新更新