积极答复者
遍历文件夹时,如何跳过拒绝访问的文件夹,继续扫描其他文件夹

问题
-
本人系统是win7。
我用directoryinfo dirs=directory.getDirectory();获取目录下的所有文件夹,然后用递归继续访问每个文件夹下的所有文件夹。
但是当访问到一些文件夹拒绝访问时(例如System Volume Information),遍历停止。
如何让该遍历继续下去?
- 已移动 Sheng Jiang 蒋晟Moderator 2010年5月7日 21:12 软件设计问题 (发件人:Visual C#)
答案
-
处理 UnauthorizedAccessException 异常
class Program
{
static void Main(string[] args)
{
foreach (string d in GetAuthorizedDirectories("C:\\"))
{
Console.WriteLine(d);
foreach (string d2 in GetAuthorizedDirectories(d))
{
Console.WriteLine(d2);
}
}
Console.ReadKey();
}public static string[] GetAuthorizedDirectories(string path)
{
try
{
return Directory.GetDirectories(path);
}
catch (UnauthorizedAccessException)
{
return new string[0];
}
}
}
问题要简单,错误须详细@错误/异常/堆栈信息+操作系统+软件版本+all the context of the issue Hope Helpful | http://www.leoworks.net- 已建议为答案 周雪峰MVP, Moderator 2010年5月8日 12:55
- 已标记为答案 zexin1000 2010年5月10日 12:03
全部回复
-
处理 UnauthorizedAccessException 异常
class Program
{
static void Main(string[] args)
{
foreach (string d in GetAuthorizedDirectories("C:\\"))
{
Console.WriteLine(d);
foreach (string d2 in GetAuthorizedDirectories(d))
{
Console.WriteLine(d2);
}
}
Console.ReadKey();
}public static string[] GetAuthorizedDirectories(string path)
{
try
{
return Directory.GetDirectories(path);
}
catch (UnauthorizedAccessException)
{
return new string[0];
}
}
}
问题要简单,错误须详细@错误/异常/堆栈信息+操作系统+软件版本+all the context of the issue Hope Helpful | http://www.leoworks.net- 已建议为答案 周雪峰MVP, Moderator 2010年5月8日 12:55
- 已标记为答案 zexin1000 2010年5月10日 12:03
-
处理 UnauthorizedAccessException 异常
class Program
{
static void Main(string[] args)
{
foreach (string d in GetAuthorizedDirectories("C:\\"))
{
Console.WriteLine(d);
foreach (string d2 in GetAuthorizedDirectories(d))
{
Console.WriteLine(d2);
}
}
Console.ReadKey();
}public static string[] GetAuthorizedDirectories(string path)
{
try
{
return Directory.GetDirectories(path);
}
catch (UnauthorizedAccessException)
{
return new string[0];
}
}
}
问题要简单,错误须详细@错误/异常/堆栈信息+操作系统+软件版本+all the context of the issue Hope Helpful | http://www.leoworks.net
主要是给了我一个try...catch...的思路,使用UnauthorizedAccessException还是不能解决问题。我try...catch...是这样用的。
directoryinfo[] dirs;
try
{
dirs=directory.getDirectories();
}
catch
{
dirs=null;
]
if(dirs!=null)
{
//继续获取当前文件夹下的目录。
}