How to recursively list all the files in a directory in C#?

前端 未结 22 3108
长发绾君心
长发绾君心 2020-11-22 00:07

How to recursively list all the files in a directory and child directories in C#?

22条回答
  •  自闭症患者
    2020-11-22 00:34

    I prefer to use DirectoryInfo because I can get FileInfo's, not just strings.

            string baseFolder = @"C:\temp";
            DirectoryInfo di = new DirectoryInfo(baseFolder);
    
            string searchPattern = "*.xml";
    
            ICollection matchingFileInfos = di.GetFiles(searchPattern, SearchOption.AllDirectories)
                .Select(x => x)
                .ToList();
    

    I do this in case in the future I need future filtering..based on the properties of FileInfo.

            string baseFolder = @"C:\temp";
            DirectoryInfo di = new DirectoryInfo(baseFolder);
    
            string searchPattern = "*.xml";
    
            ICollection matchingFileInfos = di.GetFiles(searchPattern, SearchOption.AllDirectories)
                .Where(x => x.LastWriteTimeUtc < DateTimeOffset.Now)
                .Select(x => x)
                .ToList();
    

    I can also resort back to strings if need be. (and still am future proofed for filters/where-clause stuff.

            string baseFolder = @"C:\temp";
            DirectoryInfo di = new DirectoryInfo(baseFolder);
    
            string searchPattern = "*.xml";
    
            ICollection matchingFileNames = di.GetFiles(searchPattern, SearchOption.AllDirectories)
                .Select(x => x.FullName)
                .ToList();
    

    Note that "." is a valid search pattern if you want to filer by extension.

提交回复
热议问题