C# 如何通过部分名称查找文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9428734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:23:06  来源:igfitidea点击:

How to find the file by its partial name?

c#c#-4.0

提问by Michael

How can I get the full filename?

我怎样才能得到完整的文件名?

For example:

例如:

I have a file named 171_s.jpgthat is stored on the hard disc.

我有一个名为的文件171_s.jpg存储在硬盘上。

I need to find the file by its partial name, i.e. 171_s, and get the full name.

我需要通过它的部分名称来查找文件,即171_s,并获取全名。

How can I implement this?

我该如何实施?

采纳答案by Morten N?rgaard

Here's an example using GetFiles():

下面是一个使用 GetFiles() 的例子:

static void Main(string[] args)
{
    string partialName = "171_s";
    DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(@"c:\");
    FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles("*" + partialName + "*.*");

    foreach (FileInfo foundFile in filesInDir)
    {
        string fullName = foundFile.FullName;
        Console.WriteLine(fullName);
    }    
}

回答by Jakub Konecki

You could use System.IO.Directory.GetFiles()

你可以用 System.IO.Directory.GetFiles()

http://msdn.microsoft.com/en-us/library/ms143316.aspx

http://msdn.microsoft.com/en-us/library/ms143316.aspx

public static string[] GetFiles(
    string path,
    string searchPattern,
    SearchOption searchOption
)

pathType: System.String The directory to search.

searchPatternType: System.String The search string to match against the names of files in path. The parameter cannot end in two periods ("..") or contain two periods ("..") followed by DirectorySeparatorChar or AltDirectorySeparatorChar, nor can it contain any of the characters in InvalidPathChars.

searchOptionType: System.IO.SearchOption One of the SearchOption values that specifies whether the search operation should include all subdirectories or only the current directory.

path类型:System.String 要搜索的目录。

searchPattern类型:System.String 与路径中文件名匹配的搜索字符串。该参数不能以两个句点 ("..") 结尾或包含两个句点 ("..") 后跟 DirectorySeparatorChar 或 AltDirectorySeparatorChar,也不能包含 InvalidPathChars 中的任何字符。

searchOption类型:System.IO.SearchOption SearchOption 值之一,用于指定搜索操作应包括所有子目录还是仅包括当前目录。

回答by gaurawerma

You can do it like this:

你可以这样做:

....

List<string> _filesNames;

foreach(var file in _directory)
{
    string name = GetFileName(file);
    if(name.IndexOf(_partialFileName) > 0)
    {
      _fileNames.Add(name);   
    }
}
....

回答by Jay

The answer is been already posted, however for an easy understanding here is the code

答案已经发布,但是为了便于理解,这里是代码

string folderPath = @"C:/Temp/";
DirectoryInfo dir= new DirectoryInfo(folderPath);
FileInfo[] files = dir.GetFiles("171_s*", SearchOption.TopDirectoryOnly);
foreach (var item in files)
{
    // do something here
}