在所有目录中搜索文件

时间:2017-02-27 22:10:53

标签: c#

我需要找到该文件并返回该文件的地址。我已经尝试了,但它不起作用。

你知道怎么做吗?

我正在使用此代码:

 var files = new List<string>();
 //@Stan R. suggested an improvement to handle floppy drives...
 //foreach (DriveInfo d in DriveInfo.GetDrives())
 foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
 {
    files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, actualFile, SearchOption.AllDirectories));
 }

1 个答案:

答案 0 :(得分:0)

我刚刚创建了一个快速测试,而Directory.GetFiles确实将整个路径(你正在调用的地址)返回给文件。 Microsoft文档(https://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx)表示它返回:

指定目录中文件的全名(包括路径)数组,如果没有找到文件,则为空数组。

如果你仍然需要完整的FileInfo,你可以做这样的事情...(有更多优雅的方法,但这会让你想要的。)

var files = new List<string>();
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
{
    var matchingFiles = Directory.GetFiles(d.RootDirectory.FullName, actualFile, SearchOption.AllDirectories));
    foreach (var matchedFile in matchingFiles)
    {
        var fileInfo = new FileInfo(matchedFile);

        // The newly created fileInfo will have everything you need, including path inside the FullName
        files.Add(fileInfo.FullName);
    }
}

我希望这会有所帮助。