2014-09-25 26 views
0

hye,我已经创建了一个应用程序,它将列出文件夹和子文件夹中的所有文件,但当尝试在c:\ windows下列出文件时出现此错误“UnauthorizedAccessException”。我正在使用foreach循环来对付这个错误,我已经发现了错误,但它会结束应用程序。我怎么能跳过这个错误,并转移到另一个文件。这是我所做的代码。如何排除UnauthorizedAccessException使用框架3.5

try 
     { 
      //linecount2 = Directory.GetFiles(path2).Count(); 
      //textBox1.Text = linecount2.ToString(); 

      foreach (string file in Directory.GetFiles(path2, "*.*", SearchOption.AllDirectories)) 
      { 
       currentpath = file; 
       Directory.GetAccessControl(file); 
       DateTime creationdate = File.GetCreationTime(file); 
       DateTime modidate = File.GetLastWriteTime(file); 
       textBox1.Text = "[" + file + "]" + "[" + creationdate + "]" + "[" + creationdate + "]"; 
       ReportLog(savefile); 
      } 
     } 
     catch (DirectoryNotFoundException e) 
     { 
      textBox1.Text = "[" + readpath + "]" + "[No path available]" + "[]"; 
      ReportLog(savefile); 
     } 
     catch (UnauthorizedAccessException e) 
     { 
      textBox1.Text = "[" + currentpath + "]" + "[Unauthorized Access]" + "[]"; 
      ReportLog(savefile); 
     } 

如果可能我想包括隐藏的文件。这真的有帮助。

+1

把try/catch块内部的for循环。 – DavidG 2014-09-25 09:19:12

+0

不起作用,因为错误是循环本身 – user3789007 2014-09-25 09:27:22

+0

您的问题是“SearchOption.AllDirectories”参数。尝试使用递归函数。 – Jonik 2014-09-25 10:02:38

回答

0

您的代码存在的问题是任何错误都会导致代码跳出循环。相反,把误差内捕捉for循环:

foreach (string file in Directory.GetFiles(path2, "*.*", SearchOption.AllDirectories)) 
{ 
    try 
    { 
     currentpath = file; 
     Directory.GetAccessControl(file); 
     DateTime creationdate = File.GetCreationTime(file); 
     DateTime modidate = File.GetLastWriteTime(file); 
     textBox1.Text = "[" + file + "]" + "[" + creationdate + "]" + "[" + creationdate + "]"; 
     ReportLog(savefile); 
    } 
    catch (DirectoryNotFoundException e) 
    { 
     textBox1.Text = "[" + readpath + "]" + "[No path available]" + "[]"; 
     ReportLog(savefile); 
    } 
    catch (UnauthorizedAccessException e) 
    { 
     textBox1.Text = "[" + currentpath + "]" + "[Unauthorized Access]" + "[]"; 
     ReportLog(savefile); 
    } 
} 

有你的代码中的一些其他问题,虽然,在循环中的代码不会出现做任何有用的。

0

你必须使用递归函数像这样的:

public static List<string> GetRecords(string path) 
{ 
    List<string> records; 
    try 
    { 
     records = Directory.GetFiles(path) 
      .Select(
       o => string.Format("[{0}][{1}][{2}]", o, File.GetCreationTime(o), File.GetLastWriteTime(o))) 
      .ToList(); 
     foreach (var directory in Directory.GetDirectories(path)) 
     { 
      records.AddRange(GetRecords(directory)); 
     } 
     return records; 
    } 
    catch (UnauthorizedAccessException) 
    { 
     return new List<string> {string.Format("[{0}][Unauthorized Access][]", path)}; 
    } 
    catch (DirectoryNotFoundException) 
    { 
     return new List<string> { string.Format("[{0}][No path available][]", path) }; 
    } 
}