如何在循环到Directory.GetDirectories之前动态添加其他路径? :
foreach (string d in Directory.GetDirectories(dirpath))
{
foreach (string f in Directory.GetFiles(d))
{
Console.WriteLine(f);
File.Copy(f,"");
}
}
例如,我需要它像
foreach (Directory dir in Directory.GetDirectories(dirpath).Add("another path"))
{
//My other code here....
}
怎么做?
由于
答案 0 :(得分:4)
也许是这样的:
Directory.GetDirectories(dirpath).Concat(new string[] { "another path"});
您需要在课程顶部添加using System.Linq;
。
你不能foreach (Directory dir
因为Directory
是一个静态类,你不能拥有它的实例。但您可以使用DirectoryInfo
:
var dirs = Directory.GetDirectories(dirpath)
.Concat(new string[] { "another path" })
.Select(path => new DirectoryInfo(path));
foreach (DirectoryInfo dir in dirs)
{
}
答案 1 :(得分:1)
var dir = Directory.GetDirectories(dirpath);
dir.Add("another path");
foreach (string d in dir)
{
foreach (string f in Directory.GetFiles(d))
{
Console.WriteLine(f);
File.Copy(f,"");
}
}
答案 2 :(得分:1)
为了实现这样的目标,您可以使用递归方法,如:
public void Fileprocessing(directories){
foreach (string d in directories)
{
foreach (string f in Directory.GetFiles(d))
{
Console.WriteLine(f);
File.Copy(f,"");
}
}
if(conditionToAddPath){
directories.Add("another path");
Fileprocessing(directories);
}
}
当您第一次调用初始化目录时,如:
...
string[] directories = Directory.GetDirectories(dirpath);
Fileprocessing(directories);
...
注意:这是一个伪编码的答案!!请在实施之前查看或通过添加即用型实施代码来完成此答案。
答案 3 :(得分:0)
使用SelectMany
的一种方式:
var paths = new List<string> { "path1", "path2", "path3" };
var files = paths.SelectMany(Directory.GetDirectories).SelectMany(Directory.GetFiles);
paths.Add("path4");
foreach (var file in files)
Console.WriteLine(file);
使用select
的另一种方式:
var paths = new List<string> { "path1", "path2", "path3" };
var query = from path in paths
from dir in Directory.GetDirectories(path)
from file in Directory.GetFiles(dir)
select file;
paths.Add("path4");
foreach (var file in query)
Console.WriteLine(file);