在具有相对路径的目录中生成文件列表

Generate list of files in directory with relative path

所以,我正在制作一个小应用程序,它根据命令行参数生成文件夹内的文件列表(递归)。我希望它生成具有相对路径的文件列表,以便我以后可以使用它们。参数文件夹之类的命令是c:/folder,所以我想获取文件夹内的所有内容,不包括文件夹本身。

这就是我现在得到的

c:/folder\some.exe  
c:/folder\locales\en.pak  
c:/folder\logs\client_2016.log

这就是我想要的。

some.exe  
locales\en.pak  
logs\client_2016.log

代码

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

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

    public static void ProcessFile(string path)
    {

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

将初始目录传递给您的方法?

public static void ProcessDirectory(string targetDirectory)
{
    ProcessDirectory(targetDirectory, targetDirectory);
}   

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

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

public static void ProcessFile(string path, string pathToRemove)
{
    Console.WriteLine(path.Replace(pathToRemove,""));
}

你不需要自己处理递归;您可以使用带有 SearchOption 参数的 Directory.EnumerateFiles() 的重载。

只要你的根目录以盘符或\开头,你就可以像这样做:

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));

请注意,在您枚举文件条目之前,不会获取它们。您可以将它们全部放在一个列表中,如下所示:

var listOfFiles = files.ToList();

或者您可以只使用 foreach 循环访问它们,而不先将它们放入列表中。

foreach (var file in files)
{
    // Do something with file.
}

是这样的吗?

var files = GetFiles(@"C:/tmp/", @"C:/tmp/");
return;

 public static List<string> GetFiles(string path, string basePath)
    {
      var files = System.IO.Directory.GetFiles(path).ToList().Select(m => m.Replace(basePath, "")).ToList();
      foreach (var directory in System.IO.Directory.GetDirectories(path))
      {
        files.AddRange(GetFiles(directory, basePath));
      }
      return files.Select(m => m.Replace(basePath, "")).ToList();

    }