0

私はこのコードを使用しています:

DirectoryInfo dir = new DirectoryInfo("D:\\");
foreach (FileInfo file in dir.GetFiles("*.*",SearchOption.AllDirectories))
{
    MessageBox.Show(file.FullName);
}

次のエラーが表示されます。

UnauthorizedAccessException が処理されませんでした

パス 'D:\System Volume Information\' へのアクセスが拒否されました。

どうすればこれを解決できますか?

4

3 に答える 3

1

.NETには、このコードを実行しているユーザーの特権を上書きする方法はありません。

実際には1つのオプションしかありません。管理者のみがこのコードを実行するか、管理者アカウントで実行するようにしてください。「trycatch」ブロックを配置してこの例外を処理するか、コードを実行する前に、ユーザーが管理者であることを確認することをお勧めします。

WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity);
if (currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
{
DirectoryInfo dir = new DirectoryInfo("D:\\");
foreach (FileInfo file in dir.GetFiles("*.*",SearchOption.AllDirectories))
{
MessageBox.Show(file.FullName);
}
}
于 2011-09-24T19:07:03.810 に答える
1

呼び出す前にもう1つtrycatchブロックを入れてこのメソッドを呼び出してみてください。これは、最上位フォルダーに必要な承認がないことを意味します。

     static void RecursiveGetFiles(string path)
    {
        DirectoryInfo dir = new DirectoryInfo(path);
        try
        {

            foreach (FileInfo file in dir.GetFiles())
            {
                MessageBox.Show(file.FullName);
            }
        }
        catch (UnauthorizedAccessException)
        {

            Console.WriteLine("Access denied to folder: " + path);
        }

        foreach (DirectoryInfo lowerDir in dir.GetDirectories())
        {
            try
            {
                RecursiveGetFiles(lowerDir.FullName);

            }
            catch (UnauthorizedAccessException)
            {

                MessageBox.Show("Access denied to folder: " + path);
            }
        }
    }

}
于 2011-09-24T19:44:31.637 に答える
0

システム ディレクトリを無視して、ファイル ツリーを手動で検索できます。

// Create a stack of the directories to be processed.
Stack<DirectoryInfo> dirstack = new Stack<DirectoryInfo>();
// Add your initial directory to the stack.
dirstack.Push(new DirectoryInfo(@"D:\");

// While there are directories on the stack to be processed...
while (dirstack.Count > 0)
{
    // Set the current directory and remove it from the stack.
    DirectoryInfo current = dirstack.Pop();

    // Get all the directories in the current directory.
    foreach (DirectoryInfo d in current.GetDirectories())
    {
        // Only add a directory to the stack if it is not a system directory.
        if ((d.Attributes & FileAttributes.System) != FileAttributes.System)
        {
            dirstack.Push(d);
        }
    }

    // Get all the files in the current directory.
    foreach (FileInfo f in current.GetFiles())
    {
        // Do whatever you want with the files here.
    }
}
于 2012-08-24T20:28:32.127 に答える