1

I'm looking for a way to all files and folders and files in those folders.

As an example.

if I have

- Root
+ file1
+ file2
-- Directory
-+ file1
-+ file2
---Directory
--+ file1
--+ file2

I would like to be able to output each one of those files in the program so it would be like:

root/file1
root/file2
root/Directory/file1
root/Directory/file2
root/Directory/Directory/file1
root/Directory/Directory/file2

As matching to the folder hierarchy.

Is there anyway to do this?

Thanks

Sandeep Bansal
  • 6,280
  • 17
  • 84
  • 126

4 Answers4

2

The following example does exactly what you want:-

http://www.dotnetperls.com/recursively-find-files

teenup
  • 7,459
  • 13
  • 63
  • 122
  • You need to pass your root directory path into the static `FileHelper` Class there and it will give you a List of all files and folders in that directory, you can enumerate them and use in any way you want. An enumeration is also done in the main method. Let me know if you have any doubts. – teenup Aug 24 '11 at 11:29
1

use DirectoryInfo class,FileInfo classes inside your System.IO to get these details.

 public void PrintAllFiles()
    {
        DirectoryInfo obj = new DirectoryInfo("E:\\");
        foreach (var k in obj.GetFiles())
        {
            Console.WriteLine(k.FullName);
        }
    }
Ashley John
  • 2,379
  • 2
  • 21
  • 36
1

Using Linq for some of the lifting

var di=new DirectoryInfo(folderPath);
var files=di.GetFiles("*",SearchOption.AllDirectories).Select(f=>f.FullName.Substring(di.FullName.Length+1));

miss out the substring to get the full path. Or if you just want the folder name of the root object (eg if you did c:\users\bob\fish as the directory and you just wanted fish\foldername you would do the following..

var di=new DirectoryInfo(folderPath);
var basePath=Path.GetDirectoryName(folderPath);
var files=di.GetFiles("*",SearchOptions.AllDirectorys).Select(f=>f.FullName.Substring(basePth.Length+1));

if you tag an extra .Select(f=>f.Replate(@"\","/")) on the end of the statement you can use / as the path seperator instead of \

Bob Vale
  • 18,094
  • 1
  • 42
  • 49
0

you could use System.IO.Directory.GetFiles(..,..,System.IO.SearchOption.AllDirectories) which returns an array of files and full path names and then print that array. if you need sorting you could recursively loop through directories and use System.IO.Directory.GetFiles(..,..,System.IO.SearchOption.TopDirectoryOnly) on each directory instead.

mtijn
  • 3,610
  • 2
  • 33
  • 55