Reputation: 15375
Directory.GetFiles
has an overload that takes a path and a search pattern:
var files = Directory.GetFiles(@"c:\path\to\folder", "*.txt");
to return files within a specified folder, which match the pattern. Is there a built-in .NET method that takes the path as part of the search pattern?
var files1 = Something.GetFiles(@"c:\path\to\folder\*.txt");
Upvotes: 1
Views: 170
Reputation: 67148
No, there isn't anything like that but I had this need countless times. Fortunately it's easy to write:
public string[] SearchFiles(string query)
{
return Directory.GetFiles(
Path.GetDirectoryName(query),
Path.GetFileName(query));
}
A less raw version may handle more special cases (if you need it):
public string[] SearchFiles(string query)
{
if (IsDirectory(query))
return Directory.GetFiles(query, "*.*");
return Directory.GetFiles(
Path.GetDirectoryName(query),
Path.GetFileName(query));
}
private static bool IsDirectory(string path)
{
if (String.IsNullOrWhiteSpaces(path))
return false;
if (path[path.Length - 1] == Path.DirectorySeparatorChar)
return true;
if (path[path.Length - 1] == Path.AltDirectorySeparatorChar)
return true;
if (path.IndexOfAny(Path.GetInvalidPathChars()) != -1)
return false;
return Directory.Exists(path);
}
With this new version (see IsDirectory()
code) you may use it like this:
SearchFiles(@"c:\windows\*.*");
SearchFiles(@"c:\windows\");
SearchFiles(@"c:\windows");
Upvotes: 3