如何忽略“对路径的访问被拒绝"? /C#中的UnauthorizedAccess异常? [英] How to ignore "Access to the path is denied" / UnauthorizedAccess Exception in C#?

查看:130
本文介绍了如何忽略“对路径的访问被拒绝"? /C#中的UnauthorizedAccess异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何绕过/忽略拒绝访问路径"/UnauthorizedAccess例外

How to bypass/ignore "Access to the path is denied"/UnauthorizedAccess exception

继续 以这种方法收集文件名;

and continue to collecting filenames in this method;

public static string[] GetFilesAndFoldersCMethod(string path)
{
   string[] filenames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray();
   return filenames;
}

//正在通话... ...

//Calling... ...

foreach (var s in GetFilesAndFoldersCMethod(@"C:/"))
{
    Console.WriteLine(s);
}

我的应用程序在GetFilesAndFoldersCMethod的第一行停止,并且出现异常; 拒绝访问路径'C:\ @ Logs \'.".请帮助我...

My application stops on the firstline of GetFilesAndFoldersCMethod and an exception says; "Access to the path 'C:\@Logs\' is denied.". Please help me...

谢谢

推荐答案

执行此操作的最佳方法是添加

Best way to do this is to add a Try/Catch block to handle the exception...

try
{
   string[] filenames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Select(Path.GetFullPath).ToArray();
   return filenames;
}
catch (Exception ex)
{
   //Do something when you dont have access
   return null;//if you return null remember to handle it in calling code
}

如果您是,则还可以专门处理 UnauthorizedAccessException 在此函数中执行其他代码,并且您要确保它是导致访问失败的访问异常(此异常由

you can also specifically handle the UnauthorizedAccessException if you are doing other code in this function and you want to make sure it is an access exception that causes it to fail (this exception is thrown by the Directory.GetFiles function)...

try
{
   //...
}
catch(UnauthorizedAccessException ex)
{
    //User cannot access directory
}
catch(Exception ex)
{
    //a different exception
}

编辑:正如下面的注释所指出的那样,您似乎正在通过GetFiles函数调用进行递归搜索.如果您希望它绕过任何错误并继续进行,那么您将需要编写自己的递归函数. 这里有一个很好的例子,它将满足您的需求.这是您所需要的修改.

EDIT: As pointed out in the comments below it appears you are doing a recursive search with the GetFiles function call. If you want this to bypass any errors and carry on then you will need to write your own recursive function. There is a great example here that will do what you need. Here is a modification which should be exactly what you need...

List<string> DirSearch(string sDir) 
{
   List<string> files = new List<string>();

   try  
   {
      foreach (string f in Directory.GetFiles(sDir)) 
      {
         files.Add(f);
      }

      foreach (string d in Directory.GetDirectories(sDir)) 
      {
         files.AddRange(DirSearch(d));
      }
   }
   catch (System.Exception excpt) 
   {
      Console.WriteLine(excpt.Message);
   }

   return files;
}

这篇关于如何忽略“对路径的访问被拒绝"? /C#中的UnauthorizedAccess异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆