12shadow12 12shadow12 - 1 year ago 106
C# Question

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.

This is what I get now


This is what I would like.



public static void ProcessDirectory(string targetDirectory)
// Process the list of files
string[] fileEntries = Directory.GetFiles(targetDirectory);
Parallel.ForEach(fileEntries, fileEntry =>

// Recurse into subdirectories
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
Parallel.ForEach(subdirectoryEntries, subdirectoryEntry =>

public static void ProcessFile(string path)

//string output = path.Replace(Environment.GetCommandLineArgs, ""); Something like this maybe?

Answer Source

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.

Console.WriteLine(string.Join("\n", files));

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download