您的位置:首页 > 编程语言 > C#

C#以排列组合中的“组合”方式遍历某个文件夹下的所有文件

2015-07-08 10:22 696 查看
参考自:http://blog.csdn.net/zmazon/article/details/8315418#comments

private void button1_Click(object sender, EventArgs e)
{
//temp文件夹下存放着我们的环境因子
DirectoryInfo folder = new DirectoryInfo(@"E:\work\test\data\temp");
string fileName;
FileInfo[] file = folder.GetFiles("*.asc");//只读取asc文件
string[] AttributeFiles = new string[file.Length];
for (int i = 0; i < file.Length; i++)
{
fileName = folder + "\\" + file[i].ToString();
AttributeFiles[i] = fileName;
}

int r = 3;//组合数,即C(r,n)中的r
if (null == AttributeFiles || AttributeFiles.Length == 0 || r <= 0 || r > AttributeFiles.Length)
{
MessageBox.Show("请检查文件夹的文件是否为空,参数n的设置是否有误。");
}
string[] AttributeFilesResult = new string[r];
getCombination(AttributeFiles, r, 0, AttributeFilesResult, 0);
}

private void getCombination(string[] a, int r, int begin, string[] b, int index)
{
string AttributeFile = "";
if (r == 0)
{
for (int i = 0; i < index; i++)
{
AttributeFile = AttributeFile + b[i] + " ";

}
Console.WriteLine("AttributeFile=" + AttributeFile);

}
for (int i = begin; i < a.Length; i++)
{
for (int j = 0; j < r; j++)
{
if (j % r != 0)

{
b[index] = a[i] + "#";//遍历文件,生成路径+文件名,在每个路径文件名后面加“#”号,末尾元素不加
}
else
{
b[index] = a[i];
}
}

getCombination(a, r-1,i+1,b,index+1);
}

}


程序部分输出结果如下(C(3,4),从文件夹中的4个文件中选出r=3的组合):

AttributeFile=E:\work\test\data\temp\horizc.asc# E:\work\test\data\temp\profc.asc# E:\work\test\data\temp\slope.asc
AttributeFile=E:\work\test\data\temp\horizc.asc# E:\work\test\data\temp\profc.asc# E:\work\test\data\temp\twi.asc
AttributeFile=E:\work\test\data\temp\horizc.asc# E:\work\test\data\temp\slope.asc# E:\work\test\data\temp\twi.asc
AttributeFile=E:\work\test\data\temp\profc.asc# E:\work\test\data\temp\slope.asc# E:\work\test\data\temp\twi.asc
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: