【问题标题】:Determining a FileAttribute for a file in case of "Access Denied":在“拒绝访问”的情况下确定文件的 FileAttribute:
【发布时间】:2012-08-29 21:39:01
【问题描述】:

在我的网络中,有一些文件的访问被简单地阻止了。

用户无法打开或读取文件。

当我尝试打开文件时,我收到的唯一消息是“拒绝访问”。

 bool isReadOnly = ((File.GetAttributes(Path) & FileAttributes.ReadOnly) ==   FileAttributes.ReadOnly);

我尝试了 FileAttributes 类下可用的其他选项。 “拒绝访问”没有任何匹配项。

简而言之,我如何知道在 c# 中文件是否被拒绝访问。我正在使用 WPF 和 Visual Studio .net 2010

每当我尝试通过代码访问它时,我都会得到一个异常。当我尝试手动打开它时,我得到类似“拒绝访问”的信息。

try
{
 IEs = from file in Directory.EnumerateFiles(sDirectoryToBeSearched, sValidExtensions, SearchOption.AllDirectories)
                      from str in File.ReadLines(file)
                      where (str.IndexOf(sSearchItem, StringComparison.OrdinalIgnoreCase) >= 0)
                      select file;
}

  catch
 {
      MessageBox ("Exception arised");
 }

即使使用 try catch,也不会因为 LINQ 查询而处理异常。有什么解决办法吗?>

【问题讨论】:

  • 你需要用try and catch打开它
  • 我添加了一个 try catch。即使那样也不工作!
  • catch 语句没有抛出异常。执行在“from str in File.ReadLines(file)”点中断,并且永远不会被抛出到 catch 语句!
  • 因为您正在调试,所以它停在那里。再次按 F5 或在不调试的情况下运行。无论如何,如果单个文件会导致问题,则停止所有处理。您需要分别对每个文件进行尝试和捕获。

标签: c# wpf visual-studio-2010 file access-denied


【解决方案1】:

尝试使用递归而不是使用 LINQ,这样如果文件或文件夹访问被拒绝,其余过程将继续。示例如下。

private void SearchDirectory(string folder)
{
    foreach (string file in Directory.GetFiles(folder))
    {
        try 
        {
            // do work;
        }
        catch 
        {
            // access to the file has been denied
        }
    }
    foreach (string subDir in Directory.GetDirectories(folder))
    {
        try 
        {   
             SearchDirectory(subDir);
        }
        catch 
        {
            // access to the folder has been denied
        }

    }
}

【讨论】:

  • 这是我接下来要做的!但是,使用 LINQ 的搜索操作非常快。任何想法如何用相同的查询本身来处理这些事情? !
【解决方案2】:

您不必检查FileAttributes,您需要检查安全列表。

您可以查看示例 here 以了解如何使用 FileSecurity 类。

【讨论】:

  • 如果我使用 FileAttributes,我只有三个选项读、写、读写。之后你能指导我继续吗?
猜你喜欢
  • 1970-01-01
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
  • 2021-10-17
  • 1970-01-01
  • 2016-04-28
相关资源
最近更新 更多