Reputation: 44066
I have this code
foreach (syncspec.Attribute attr in attributes)
{
string fullPath = location + "\\" + attr.link;
if (File.Exists(fullPath))
}
and i am checking a know location and an example fullpath is listed below
// fullPath = "C:\\Users\\matt\\Desktop\\shard\\all/file30005"
What i want to do is look in the all folder and any subfolders within the all folder...any ideas on how to achieve this
Upvotes: 0
Views: 1029
Reputation: 62246
First do not use simple concatenation on paths, but use Path.Combine:
string parentDirPath = Path.Combine(location , attr.link);
And second, for iterating over all sub-directories, can use
Directory.EnumerateDirectories
Example:
foreach (var dir in Directory.EnumerateDirectories(parentDirPath))
{
//do something here
}
Upvotes: 1
Reputation: 3717
This solution is a bit heavier, but I use a variant of it because it allows you to catch any exceptions while searching and continue. GetFiles()
will error out entirely if it encounters a directory that it does not have permissions to traverse.
Check this: Safe File Enumeration
Upvotes: 0
Reputation: 1965
You can either use GetFiles(..) as suggested by the others or use a recursive method like this (fully working solution btw):
bool FileExists(string path, string filename)
{
string fullPath = Path.Combine(path, filename);
return File.Exists(fullPath) && Directory.GetDirectories(path).All(x => FileExists(x, filename));
}
Upvotes: 1
Reputation: 216290
Your friend is
DirectoryInfo.GetFiles("filename", SearchOption.AllDirectories);
as in this example:
DirectoryInfo info = new DirectoryInfo(location);
FileInfo[] results = info.GetFiles(attr.Link, SearchOption.AllDirectories);
foreach(FileInfo fi in results)
....
See the MSDN docs for reference
Upvotes: 1
Reputation: 3994
System.IO.Directory.GetFiles(location, attr.link, SearchOption.AllDirectories);
Read more on GetFiles via MSDN: http://msdn.microsoft.com/en-us/library/ms143316
Upvotes: 4