忽略Directory.GetFiles上的UnauthorizedAccessException [英] Ignore UnauthorizedAccessException on Directory.GetFiles
问题描述
是否有一种简便的方法来忽略文件,我无权访问?
我有时会收到文件的UnauthorizedAccessException.如果我处理了,我的方法就会退出.
代码如下:
Is there an easy way to ignore files, I don''t have access to?
I get sometimes an UnauthorizedAccessException for files. If I handle it, my method will be quit.
Here''s the code:
string[] files;
files = Directory.GetFiles("C:\MyDir", "*.*", SearchOption.AllDirectories);
推荐答案
try
{
string[] files = Directory.GetFiles("C:\MyDir", "*.*", SearchOption.AllDirectories);
// do something with your file array
}
catch (UnauthorizedAccessException)
{
// this eats the exception but it will still stop
}
catch (Exception ex)
{
// you can handle all other exceptions here
}
GetFileSystemEntries
也会抛出UnauthorizedAccessException
,所以我认为通过使用它不会获得任何好处.我也不知道文件数组的状况-它会继续进行操作还是在异常处停止?我不得不尝试运行一些代码,但是再次,您可以自己执行.
GetFileSystemEntries
will also throw the UnauthorizedAccessException
, so I don''t think you''ll gain anything by using it instead. I also don''t know the condition of the array of files - does it continue on with the operation or stop at the exception? I''d have to try running some code, but then again, you can do that yourself.
使用递归而不是SearchOption.AllDirectories值.
例如
http://www.dotnetperls.com/recursively-find-files [ http://msdn.microsoft.com/en-us/library/07wt70x2.aspx [ ^ ]
这样,您可以尝试捕获具有权限问题的任何目录,然后继续执行下一个目录.
在堆栈溢出中也可以看到此问题,与您的问题相同
http://stackoverflow.com/questions/172544/ignore-文件夹文件何时拒绝目录访问 [
Use recursion rather than the SearchOption.AllDirectories value.
e.g.
http://www.dotnetperls.com/recursively-find-files[^]
Or MSDN version
http://msdn.microsoft.com/en-us/library/07wt70x2.aspx[^]
This way, you can just try-catch on any directories with permissions issues and continue on to the next directory.
See this on stack overflow as well, same issue as you
http://stackoverflow.com/questions/172544/ignore-folders-files-when-directory-getfiles-is-denied-access[^]
我相信如果您没有足够的权限,就会发生此错误,这意味着您或应用程序无法浏览.
您也可以尝试查看此内容,但它也可能会出错.
Directory.GetFileSystemEntries [
I believe the error occurs when you don''t have sufficient rights, meaning you or the app is not allowed to browse it.
You could also try looking at this but it''ll probably error too.
Directory.GetFileSystemEntries [^]
这篇关于忽略Directory.GetFiles上的UnauthorizedAccessException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!