c# - 删除文件时发生错误:拒绝访问路径
问题描述
我正在尝试从为其分配了完全控制权的文件夹中删除文件,但有时用户仍会拒绝访问该文件夹。
有时并非每次都会发生这种情况。
注意:在删除之前,我们检查文件是否正在使用。以下是两个函数。
删除文件 :
public static Boolean DeleteFile(string filePath)
{
bool isFileInUse = false;
if (File.Exists(filePath))
{
FileInfo currentFileInfo = new FileInfo(filePath);
if (!IsFileLocked(currentFileInfo))
File.Delete(filePath);
else
isFileInUse = true;
}
return isFileInUse;
}
IsFileLocked:
private static Boolean IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
//Don't change FileAccess to ReadWrite,
//because if a file is in readOnly, it fails.
stream = file.Open
(
FileMode.Open,
FileAccess.Read,
FileShare.None
);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
即使在完全控制之后,谁能告诉我为什么有时会发生此错误?
注意:当我们尝试删除文件时,我们首先需要检查文件是否正在使用中。
解决方案
推荐阅读
- python - 如何在 OpenCV 中读取 .tif 图像
- c - 如何修复“分段错误(核心转储)”错误
- python - Plotly AttributeError:“Figure”对象没有属性“update_layout”
- azure - 从 Azure 流分析的查询语言中指定属性值的列和行
- docker - 无法反序列化主题的数据
- drupal - Drupal 8 - 节点引用迁移到实体引用类型
- django - Django 休息框架。如何序列化模型名称和实例值而不是 content_type 和 object_id?
- java - 如何访问铬(或任何其他浏览器)cookie
- python - sqlalchemy 错误插入时缺少绑定参数,但在 Workbench 中有效
- javascript - RXJS如何实现平滑滚动