C#如何忽略异常继续执行代码呢?

爱在今世 2013-03-12 05:06:20
            string str = "c:\\";
int i = 0;
foreach (string s in Directory.GetFiles(str, "*", SearchOption.AllDirectories))
{
i += 1;

}
像以上代码。一运行就会报错,说是某某目录拒绝访问。所以我想问问有没有什么方法可以忽略这个异常让程序继续运行,跳到下一个目录呢?
...全文
3239 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
cjh200102 2013-03-14
  • 打赏
  • 举报
回复
有异常还继续运行?
Wang-Yucai 2013-03-14
  • 打赏
  • 举报
回复
直接try...catch....

    try{
    }
    catch{}

    这样就O了
爱在今世 2013-03-14
  • 打赏
  • 举报
回复
已经将rinall 贴出的代码进行了改编成功的搜索出了全部文件名。谢谢rinall
rinall 2013-03-14
  • 打赏
  • 举报
回复
引用 6 楼 showyusy 的回复:
引用 3 楼 rinall 的回复:public int ddddd(string path) { int i = 0; string[] strFile = Directory.GetFiles(path); i = strFile.Length; ……
系统查询会隐藏一些系统重要文件 这是常识
孙大诚_SunRobin 2013-03-14
  • 打赏
  • 举报
回复
try catch +1
申江渔夫 2013-03-14
  • 打赏
  • 举报
回复
LZ这段代码是无法通过忽略异常而达到你希望的目的。 因为MSDN上有写“when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array.”,就是说GetFiles会把所有的文件名一次全取出来,若是有异常,则这个方法运行失败。 你可以试着把这个方法从循环内移出来,比如: string[] files = Directory.GetFiles(@"C:\", "*", SearchOption.AllDirectories); 再执行,你会发现程序在这里就出错了,与下面的循环没有关系。
爱在今世 2013-03-12
  • 打赏
  • 举报
回复
引用 3 楼 rinall 的回复:
public int ddddd(string path) { int i = 0; string[] strFile = Directory.GetFiles(path); i = strFile.Length; string[] strDirect……
你太强大了,系统只扫描出18W多个文件,但是你这招扫描出了19W多个。话说如果要获取的是全部文件的完整路径该怎么整?
爱在今世 2013-03-12
  • 打赏
  • 举报
回复
就是这个
爱在今世 2013-03-12
  • 打赏
  • 举报
回复
不是权限的问题,那个目录下面有个快捷方式的标记,我用超级管理员都不能访问
rinall 2013-03-12
  • 打赏
  • 举报
回复
public int ddddd(string path) { int i = 0; string[] strFile = Directory.GetFiles(path); i = strFile.Length; string[] strDirectory = Directory.GetDirectories(path); foreach (string item in strDirectory) { try { i += ddddd(item); } catch (Exception) { continue; } } return i; }
  • 打赏
  • 举报
回复
另外,你的目录设置了权限,请重新设置一下文件的权限。
  • 打赏
  • 举报
回复
try catch 请参考->错误处理机制

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧