0

I have a directory which contains many subdirectories. For example:

Emp1
 Acc
 profile
   pro1.xml
   pro2.xml
 data
Emp2
 Acc
 profile
   pro1.xml
   pro2.xml
 data
Emp3
 Acc
 profile
   pro1.xml
   pro2.xml
 data

I want to write a foreach loop so I get only files which reside in the profile folder. For example:

 foreach string filename in directory.getdirectories(filepat){
        //code.
  }

Can someone please help me create a search pattern to do this?

Filburt
  • 17,626
  • 12
  • 64
  • 115
Hiren Visavadiya
  • 485
  • 1
  • 3
  • 15
  • So you want all files from each of the three profile folders? What do you want to do with the files? Add them to a list? – Bridge May 24 '12 at 09:02
  • Maybe a recursive method will be a solution. – chaliasos May 24 '12 at 09:03
  • How to get files: http://stackoverflow.com/questions/4466756/get-files-from-multiple-directories (about performances: http://stackoverflow.com/questions/9831641/more-efficient-method-of-getting-directory-size/9831721#9831721) and how to get executable path: http://stackoverflow.com/questions/837488/how-can-i-get-the-applications-path-in-net-in-a-console-app – Adriano Repetti May 24 '12 at 09:04
  • [How to recursively list all the files in a directory in C#?](http://stackoverflow.com/questions/929276/how-to-recursively-list-all-the-files-in-a-directory-in-c) Just check if the `Directory` name is `profile`. – chaliasos May 24 '12 at 09:09

4 Answers4

1

EDIT after Question Edited....

var directoryInfo = new DirectoryInfo(@"c:\temp\stackoverflow");
foreach (var element in dinfo.GetDirectories(@"profile", SearchOption.AllDirectories).SelectMany(x => x.GetFiles()))
{
    Console.WriteLine (element);
}

Like this?

jjchiw
  • 4,375
  • 1
  • 29
  • 30
1

I wrote some fluent extensions to files and directories that let you do this nicely with linq, Take a look here: http://blog.staticvoid.co.nz/2011/11/staticvoid-io-extentions-nuget.html

or download from nuget using Install-Package StaticVoid.Core.IO

diretory.Directories().SelectMany(d => 
   d.Directory(di => di.Name == "Acc")
       .Directory(di => di.Name == "profile").Files());
undefined
  • 33,537
  • 22
  • 129
  • 198
0

It may be what you want...

 string [] dirname = Directory.GetDirectories(path){
                 foreach( string s in dirname)
                 {
                   if(s.Contains("profile"))
                   {
                     //do your work
                   }
                 }
Md Kamruzzaman Sarker
  • 2,387
  • 3
  • 22
  • 38
0

Maybe you could try something like the following:

 IEnumerable<string> directories = Directory.GetDirectories("PATH", "*.*", SearchOption.AllDirectories).Where(d => d == "ProfileFolder");
 foreach (string directory in directories)
 {
     string[] files = Directory.GetFiles(directory, "*.*", SearchOption.TopDirectoryOnly);
 }
Tomtom
  • 9,087
  • 7
  • 52
  • 95