Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the file by its partial name?

Tags:

c#

c#-4.0

How can I get the full filename?

For example:

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

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

How can I implement this?

like image 713
Michael Avatar asked Feb 24 '12 09:02

Michael


People also ask

How do I find a file with a specific name?

Finding files by name is probably the most common use of the find command. To find a file by its name, use the -name option followed by the name of the file you are searching for.

How do we search for all the files whose name start from test in the home directory?

Finding Files with bat Anywhere To search your whole computer, use / . To search your home directory, use ~ , or the full name of your home directory. (The shell expands ~ to your home directory's fully qualified path.)

How will you find a file name containing fee in the name in Linux?

Your answer You can use “grep” command to search string in files. Alternatively, You can also also use the "find " command to display files with specific string. Hope this answer help you. To learn more about Linux, enroll in Linux administration course online today.

How do I get the filename from the file path?

To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);


2 Answers

Here's an example using 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);     }     } 
like image 70
Morten Nørgaard Avatar answered Sep 20 '22 19:09

Morten Nørgaard


Update - Jakub answer is more efficient way to do. ie, use System.IO.Directory.GetFiles() http://msdn.microsoft.com/en-us/library/ms143316.aspx

The answer has 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 } 
like image 30
Jay Avatar answered Sep 21 '22 19:09

Jay