Reputation: 6394
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
Upvotes: 1
Views: 1652
Reputation: 18474
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 \
Upvotes: 1
Reputation: 2453
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);
}
}
Upvotes: 1
Reputation: 7667
The following example does exactly what you want:-
http://www.dotnetperls.com/recursively-find-files
Upvotes: 2
Reputation: 3678
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.
Upvotes: 0