Generate list of files in directory with relative path
So, I'm making a little app which generates a list of files inside a folder (recursive) from a command line argument. I would like it to generate the file list with relative paths so I can use them later. The command like argument folder is c:/folder, so I want to get everything inside the folder not including the folder itself.
You don't need to handle the recursion yourself; you can use the overload of Directory.EnumerateFiles() which takes a SearchOption parameter.
Provided that your root starts with a drive letter or \\, you can do what you want like this:
string root = @"D:\Test\";
var files = Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories)
.Select(path => path.Replace(root, ""));
// Now files contains all the file names you want, with the root removed.
Note that the file entries are not fetched until you enumerate them. You can put them all in a list like so:
var listOfFiles = files.ToList();
Or you can just use foreach to iterate over them without putting them in a list first.
foreach (var file in files)
// Do something with file.