且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#使用GetFiles返回完整路径

更新时间:2022-06-19 22:31:25

FileInfo包含FullName属性,您可以使用该属性来检索文件的完整路径

FileInfo contains a FullName property, which you can use to retrieve full path to a file

var fullNames = files.Select(file => file.FullName).ToArray();

检查

此代码在我的计算机上:

Check

This code on my machine:

FileInfo[] files = null;
string path = @"C:\temp";
DirectoryInfo folder = new DirectoryInfo(path);
files = folder.GetFiles("*.*", SearchOption.AllDirectories);

//you need string from FileInfo to denote full path
IEnumerable<string> fullNames = files.Select(file => file.FullName);

Console.WriteLine ( string.Join(Environment.NewLine, fullNames ) );

打印

C:\temp\1.dot 
C:\temp\1.jpg 
C:\temp\1.png 
C:\temp\1.txt 
C:\temp\2.png 
C:\temp\a.xml 
...

完整解决方案

您的问题的解决方案可能看起来像这样:

Full solution

The solution to your problem might look like this:

string path = @"C:\temp";
DirectoryInfo folder = new DirectoryInfo(path);
var directories = folder.GetDirectories("*.*", SearchOption.AllDirectories);


IEnumerable<string> directoriesWithDot = 
 directories.Where(dir => dir.Name.Contains("."))
            .Select(dir => dir.FullName);


IEnumerable<string> filesInDirectoriesWithoutDot = 
 directories.Where(dir => !dir.Name.Contains("."))
            .SelectMany(dir => dir.GetFiles("*.*", SearchOption.TopDirectoryOnly))
            .Select(file => file.FullName);


Console.WriteLine ( string.Join(Environment.NewLine, directoriesWithDot.Union(filesInDirectoriesWithoutDot) ) );