0

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

Omar
  • 16,329
  • 10
  • 48
  • 66
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321
  • 1
    Similar problem and solution here: http://stackoverflow.com/questions/3994448/how-to-check-if-a-specific-file-exists-in-directory-or-any-of-its-subdirectories – Davio May 15 '12 at 14:20

5 Answers5

4
System.IO.Directory.GetFiles(location, attr.link, SearchOption.AllDirectories);

Read more on GetFiles via MSDN: http://msdn.microsoft.com/en-us/library/ms143316

roken
  • 3,946
  • 1
  • 19
  • 32
1

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

Steve
  • 213,761
  • 22
  • 232
  • 286
1

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));
}
Brunner
  • 1,945
  • 23
  • 26
1

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
}
Tigran
  • 61,654
  • 8
  • 86
  • 123
0

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

Grant H.
  • 3,689
  • 2
  • 35
  • 53