首页 > 解决方案 > 删除文件时发生错误:拒绝访问路径

问题描述

我正在尝试从为其分配了完全控制权的文件夹中删除文件,但有时用户仍会拒绝访问该文件夹。

有时并非每次都会发生这种情况。

注意:在删除之前,我们检查文件是否正在使用。以下是两个函数。

删除文件 :

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;
}

即使在完全控制之后,谁能告诉我为什么有时会发生此错误?

注意:当我们尝试删除文件时,我们首先需要检查文件是否正在使用中。

标签: c#.netfiledelete-file

解决方案


推荐阅读