I am trying to use the Directory.GetFiles()
method to retrieve a list of files of multiple types, such as mp3
\'s and jpg
\'s. I have t
I had the same problem and couldn't find the right solution so I wrote a function called GetFiles:
///
/// Get all files with a specific extension
///
/// string list of all the extensions
/// string of the location
/// array of all the files with the specific extensions
public string[] GetFiles(List extensionsToCompare, string Location)
{
List files = new List();
foreach (string file in Directory.GetFiles(Location))
{
if (extensionsToCompare.Contains(file.Substring(file.IndexOf('.')+1).ToLower())) files.Add(file);
}
files.Sort();
return files.ToArray();
}
This function will call Directory.Getfiles()
only one time.
For example call the function like this:
string[] images = GetFiles(new List{"jpg", "png", "gif"}, "imageFolder");
EDIT: To get one file with multiple extensions use this one:
///
/// Get the file with a specific name and extension
///
/// the name of the file to find
/// string list of all the extensions
/// string of the location
/// file with the requested filename
public string GetFile( string filename, List extensionsToCompare, string Location)
{
foreach (string file in Directory.GetFiles(Location))
{
if (extensionsToCompare.Contains(file.Substring(file.IndexOf('.') + 1).ToLower()) &&& file.Substring(Location.Length + 1, (file.IndexOf('.') - (Location.Length + 1))).ToLower() == filename)
return file;
}
return "";
}
For example call the function like this:
string image = GetFile("imagename", new List{"jpg", "png", "gif"}, "imageFolder");