如何递归列出C#目录中的所有文件?

本文翻译自:How to recursively list all the files in a directory in C#?

如何递归列出C#中目录和子目录中的所有文件?


#1楼

参考:https://stackoom.com/question/3TKk/如何递归列出C-目录中的所有文件


#2楼

In .NET 4.5, at least, there's this version that is much shorter and has the added bonus of evaluating any file criteria for inclusion in the list: 至少在.NET 4.5中,此版本要短得多,并且具有评估包含在列表中的任何文件条件的额外好处:

    /// </remarks>
    public static IEnumerable<string> GetAllFiles(string path, Func<FileInfo, bool> checkFile = null)
    {
        string mask = Path.GetFileName(path);
        if (string.IsNullOrEmpty(mask))
            mask = "*.*";
        path = Path.GetDirectoryName(path);
        string[] files = Directory.GetFiles(path, mask, SearchOption.AllDirectories);
        foreach (string file in files)
        {
            if (checkFile == null || checkFile(new FileInfo(file)))
                yield return file;
        }
    }

Use like: 使用方式如下:

        string folder = Config.TestInput();
        string mask = folder + "*.*";
        var list = UT.GetAllFiles(mask, (info) => Path.GetExtension(info.Name) == ".html").ToList();
        Assert.AreNotEqual(0, list.Count);
        var lastQuarter = DateTime.Now.AddMonths(-3);
        list = UT.GetAllFiles(mask, (info) => info.CreationTime >= lastQuarter).ToList();
        Assert.AreNotEqual(0, list.Count);

#3楼

Some excellent answers but these answers did not solve my issue. 一些很好的答案,但是这些答案并不能解决我的问题。

As soon as a folder permission issue arises: "Permission Denied" the code fails. 一旦出现文件夹权限问题:“权限被拒绝”,代码将失败。 This is what I used to get around the "Permission Denied" issue: 这是我用来解决“权限被拒绝”问题的方法:

private int counter = 0;

    private string[] MyDirectories = Directory.GetDirectories("C:\\");

    private void ScanButton_Click(object sender, EventArgs e)
    {
        Thread MonitorSpeech = new Thread(() => ScanFiles());
        MonitorSpeech.Start();
    }

    private void ScanFiles()
    {
        string CurrentDirectory = string.Empty;

        while (counter < MyDirectories.Length)
        {
            try
            {
                GetDirectories();
                CurrentDirectory = MyDirectories[counter++];
            }
            catch
            {
                if (!this.IsDisposed)
                {
                    listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + CurrentDirectory); });
                }
            }
        }
    }

    private void GetDirectories()
    {
        foreach (string directory in MyDirectories)
        {
            GetFiles(directory);
        }
    }

    private void GetFiles(string directory)
    {
        try
        {
            foreach (string file in Directory.GetFiles(directory, "*"))
            {
                listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(file); });
            }
        }
        catch
        {
            listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + directory); });
        }
    }

Hope this helps others. 希望这对其他人有帮助。


#4楼

In Framework 2.0 you can use (It list files of root folder, it's best the most popular answer): 在Framework 2.0中,您可以使用(列出根文件夹的文件,最好是最受欢迎的答案):

static void DirSearch(string dir)
{
    try
    {
        foreach (string f in Directory.GetFiles(dir))
            Console.WriteLine(f);
        foreach (string d in Directory.GetDirectories(dir))
        {
            Console.WriteLine(d);
            DirSearch(d);
        }

    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

#5楼

Here's my angle on it, based on Hernaldo's, if you need to find files with names of a certain pattern, such as XML files that somewhere in their name contain a particular string: 如果您需要查找具有特定模式名称的文件,例如在其名称中某处包含特定字符串的XML文件,那么基于Hernaldo,这是我的看法。

// call this like so: GetXMLFiles("Platypus", "C:\\");
public static List<string> GetXMLFiles(string fileType, string dir)
{
    string dirName = dir; 
    var fileNames = new List<String>();
    try
    {
        foreach (string f in Directory.GetFiles(dirName))
        {
            if ((f.Contains(fileType)) && (f.Contains(".XML")))
            {
                fileNames.Add(f);
            }
        }
        foreach (string d in Directory.GetDirectories(dirName))
        {
            GetXMLFiles(fileType, d);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    return fileNames;
}

#6楼

Here is a version of B. Clay Shannon's code not static for excel-files: 这是B. Clay Shannon的代码对于excel文件不是静态的:

class ExcelSearcher
{
    private List<string> _fileNames;

    public ExcelSearcher(List<string> filenames)
    {
        _fileNames = filenames;
    }
    public List<string> GetExcelFiles(string dir, List<string> filenames = null)
    {

        string dirName = dir;
        var dirNames = new List<string>();
        if (filenames != null)
        {
            _fileNames.Concat(filenames);
        }
        try
        {
            foreach (string f in Directory.GetFiles(dirName))
            {
                if (f.ToLower().EndsWith(".xls") || f.ToLower().EndsWith(".xlsx"))
                {
                    _fileNames.Add(f);
                }
            }
            dirNames = Directory.GetDirectories(dirName).ToList();
            foreach (string d in dirNames)
            {
                GetExcelFiles(d, _fileNames);
            }
        }
        catch (Exception ex)
        {
            //Bam
        }
        return _fileNames;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值