2009-07-12 27 views
1

我想迭代我的開始菜單上的項目,但我不斷收到UnauthorizedAccessException。我是目錄的所有者,我的用戶是管理員。UnauthorizedAccessException在我自己的目錄

這裏是我的方法(這是一個dll項目):

// root = C:\Users\Fernando\AppData\Roaming\Microsoft\Windows\Start Menu 
private void walkDirectoryTree(DirectoryInfo root) { 
    try { 
     FileInfo[] files = root.GetFiles("*.*"); 
     foreach (FileInfo file in files) { 
      records.Add(new Record {Path = file.FullName}); 
     } 
     DirectoryInfo[] subDirectories = root.GetDirectories(); 
     foreach (DirectoryInfo subDirectory in subDirectories) { 
      walkDirectoryTree(subDirectory); 
     } 
    } catch (UnauthorizedAccessException e) { 
     // do some logging stuff 
     throw; //for debugging 
    } 
} 

的代碼,當它開始遍歷子目錄失敗。我還應該做什麼?我已經嘗試創建清單文件,但它不起作用。另一點(如果是相關的):我只是運行一些單元測試與視覺工作室(這是作爲管理員執行)。

回答

4

根據您的描述,在啓用UAC的情況下運行時,您的用戶似乎無法訪問該目錄。你的代碼沒有什麼固有的錯誤,在這種情況下的行爲是通過設計的。在代碼中沒有任何東西可以解決您的帳戶無法訪問當前正在運行的上下文中的這些目錄的事實。

你需要做的是考慮你無權訪問的目錄。最好的方法可能是通過添加一些擴展方法。例如

public static FileInfo[] GetFilesSafe(this DirectoryRoot root, string path) { 
    try { 
    return root.GetFiles(path); 
    } catch (UnauthorizedAccessException) { 
    return new FileInfo[0]; 
    } 
} 
+0

使用擴展方法是解決異常的一個很好的解決方案。要獲得我的開始菜單上的「缺失」條目,我已經按照註冊表鍵「HKLM \ Software \ Microsoft \ Windows \ CurrentVersion \ Explorer \ Shell \ Folders \ Common Start Menu'.Thnx! – Fernando 2009-07-14 01:47:07

相關問題