所以,我正在创建一个小应用程序,它从命令行参数生成文件夹内的文件列表(递归)。我希望它生成具有相对路径的文件列表,以便我以后可以使用它们。像参数文件夹这样的命令是c:/文件夹,所以我想让文件夹里面的所有内容都不包括文件夹本身。
这就是我现在得到的
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);
}
答案 0 :(得分:1)
您不需要自己处理递归;您可以使用带有Directory.EnumerateFiles()
参数的SearchOption
重载。
如果您的根以驱动器号或\\
开头,您可以按照以下方式执行操作:
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.
}
答案 1 :(得分:0)
将初始目录传递给您的方法?
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,""));
}
答案 2 :(得分:0)
这样的东西?
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();
}