搜索用C#文件 [英] Searching for a file with C#

查看:102
本文介绍了搜索用C#文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是寻找在C#透过程式设计文件的最快方式。我知道文件的相对位置,可以说,它的abcd\efgh\test.txt。我也知道,这个文件是在我的 E:\驱动器。 ABCD是在电子商务的一些目录的子目录:\驱动器

What would be the fastest way to search for a file programtically in C#. I know the relative location of the file, lets say its "abcd\efgh\test.txt". I also know that this file is on my E:\ drive. "abcd" is a subdirectory on some directory in E:\ drive.

感谢

推荐答案

既然你知道你要搜索的根目录和文件名字符串模式,您可以创建一个DirectoryInfo中与根目录:

Since you know the root directory you want to search and a string pattern for a filename, you can create a DirectoryInfo with the root directory:

DirectoryInfo dir = new DirectoryInfo(@"E:\");



然后调用的GetFiles()来获得所有的比赛。 。通过 SearchOption.AllDirectories 将确保搜索是递归的

And then call GetFiles() to get all the matches. Passing SearchOption.AllDirectories will ensure the search is recursive.

List<FileInfo> matches = 
    new List<FileInfo>(dir.GetFiles(partialFilename, 
        SearchOption.AllDirectories));



或者,如果你知道路径(而不是文件名)的一部分:

Or if you know part of the path (instead of the filename):

List<DirectoryInfo> matches =
    new List<DirectoryInfo>(dir.GetDirectories(partialDirectoryName,
        SearchOption.AllDirectories));



然后你就可以从那里导航到该文件。

And then you can navigate to the file from there.

这篇关于搜索用C#文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆