Reputation: 13616
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?
Upvotes: 49
Views: 117750
Reputation: 21
Simple as that:
string path = @"C:\example\directory";
string searchPattern = "*171_s*";
string[] filePaths = Directory.GetFiles(path, searchPattern,SearchOption.AllDirectories);
Upvotes: 1
Reputation: 1889
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
}
Upvotes: 19
Reputation: 2809
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);
}
}
Upvotes: 89
Reputation: 1826
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);
}
}
....
Upvotes: 3
Reputation: 46008
You could use System.IO.Directory.GetFiles()
http://msdn.microsoft.com/en-us/library/ms143316.aspx
public static string[] GetFiles(
string path,
string searchPattern,
SearchOption searchOption
)
path Type: System.String The directory to search.
searchPattern Type: 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.
searchOption Type: System.IO.SearchOption One of the SearchOption values that specifies whether the search operation should include all subdirectories or only the current directory.
Upvotes: 12