How to find the file by its partial name?
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
}
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);
}
}
....
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.