列出根目录下的所有文件

Listing all the files in root directory

感谢您的支持!我现在有了扫描所有文件夹、子文件夹和文件的工作代码。只剩下一个问题需要解决:

我没有得到初始根目录中的文件,只有子文件夹。我还需要为这些文件调用FileInfo

如何在不修改代码太多的情况下解决这个问题?

private void ScanFolder(String prefix, String path)
{
    try
    {
        string user = System.IO.File.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
        DirectoryInfo di = new DirectoryInfo(path);

        foreach (var dir in new DirectoryInfo(path).GetDirectories("*", SearchOption.TopDirectoryOnly))
        {
            listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + dir.Name + " (" + dir.Name.Length.ToString() + ")   "); });

            foreach (FileInfo fileInfo in dir.GetFiles())
            {
                listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + fileInfo.Name + " (" + fileInfo.Name.Length.ToString() + ")   " + user + "   " + fileInfo.FullName + " (" + fileInfo.FullName.Length.ToString() + ")"); });
            }

            ScanFolder(prefix + "—", dir.FullName);
        }
    }
    catch
    {
        if (!this.IsDisposed)
        {
            listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + path); });
        }
    }
}

输出:

** 文件应该在这里 **
13-9-legacy_vista_win7_64_dd_ccc_whql (37)
Radeon-Software-Adrenalin-18.3.3-MinimalSetup-180319_web (56)
—Bin (3)
——本地化(12)
————cs(2)
————da_DK (5)
———德(2)
————el_GR (5)
————es_ES (5)

到目前为止,您只查找根目录中的目录。
您还想枚举文件:

private void ScanFolder(String prefix, String path)
{
    try
    {
        string user = System.IO.File.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
        DirectoryInfo di = new DirectoryInfo(path);

        // Enumerate through the files here
        foreach (FileInfo fileInfo in di.GetFiles())
        {
            listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + fileInfo.Name + " (" + fileInfo.Name.Length.ToString() + ")   " + user + "   " + fileInfo.FullName + " (" + fileInfo.FullName.Length.ToString() + ")"); });
        }
        // ----

        // You can also use the DirectoryInfo you created earlier here
        foreach (var dir in new di.GetDirectories("*", SearchOption.TopDirectoryOnly))
        {
            listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + dir.Name + " (" + dir.Name.Length.ToString() + ")   "); });

            foreach (FileInfo fileInfo in dir.GetFiles())
            {
                listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + fileInfo.Name + " (" + fileInfo.Name.Length.ToString() + ")   " + user + "   " + fileInfo.FullName + " (" + fileInfo.FullName.Length.ToString() + ")"); });
            }

            ScanFolder(prefix + "—", dir.FullName);
        }
    }
    catch
    {
        if (!this.IsDisposed)
        {
            listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + path); });
        }
    }
}