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?
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.
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.)
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.
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);
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); } }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With