1

So here is what I have in there now. I am getting a whole lot of red lines in this and not sure why. I need to know how to take the code you all gave me below and put it in to a checkbox method so that it runs when you hit a button labeled next.

public Question()
{
    InitializeComponent();
}

private void Question_Load(object sender, EventArgs e)
{}

private void Exit_Click(object sender, EventArgs e)
{
    Close();
}

private void UnRe_CheckedChanged(object sender, EventArgs e)
{
    if (UnRe.Checked == true)
    {
        string rootDirectory = System.IO.DriveInfo.GetDrives()[0].RootDirectory.FullName;

        string[] files = System.IO.Directory.GetFiles( rootDirectory,
                        "file.exe", System.IO.SearchOption.AllDirectories);
    }
}// closes class

private void Infection_CheckedChanged(object sender, EventArgs e)
{
    if (Support.Checked == true)
    {}
}

private void Other_CheckedChanged(object sender, EventArgs e)
{}

private void Next_Click(object sender, EventArgs e)
{}

IEnumerable<string> GetAllAuthorizedFiles(string root, string searchPattern)
{
    foreach (var fname in GetAuthorizedFiles(root, searchPattern))
        yield return fname;

    foreach (var dir in GetAuthorizedDirectories(root))
    {
        foreach (var fname in GetAllAuthorizedFiles(dir, searchPattern))
            yield return fname;
    }
}

string[] GetAuthorizedDirectories(string root)
{
    try
    {
        return Directory.GetDirectories(root);
    }
    catch (UnauthorizedAccessException)
    {
        return new string[0];
    }
}

string[] GetAuthorizedFiles(string root, string searchPattern)
{
    try
    {
        return Directory.GetFiles(root, searchPattern);
    }
    catch (UnauthorizedAccessException)
    {
        return new string[0];
    }
}
4

1 回答 1

1

如果时间不是您所说的问题,您可以遍历所有目录以获取其文件。每当您遇到UnauthorizedAccessExcpetion时,您只需忽略该目录并移至下一个目录。

正如 Hans Passant 所建议的,这是递归文件枚举方法的实现:

IEnumerable<string> GetAllAuthorizedFiles(string root, string searchPattern)
{
    foreach (var fname in GetAuthorizedFiles(root, searchPattern))
        yield return fname;

    foreach (var dir in GetAuthorizedDirectories(root))
    {
        foreach (var fname in GetAllAuthorizedFiles(dir, searchPattern))
            yield return fname;
    }
}

string[] GetAuthorizedDirectories(string root)
{
    try
    {
        return Directory.GetDirectories(root);
    }
    catch (UnauthorizedAccessException)
    {
        return new string[0];
    }
}

string[] GetAuthorizedFiles(string root, string searchPattern)
{
    try
    {
        return Directory.GetFiles(root, searchPattern);
    }
    catch (UnauthorizedAccessException)
    {
        return new string[0];
    }
}

以下是您从代码中调用它的方式:

string[] files = GetAllAuthorizedFiles(rootDirectory, "File.exe").ToArray();
于 2013-07-20T18:00:19.847 回答