2014-09-25 31 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) }; 
    } 
}