更好的方法 - GetFiles - c#

时间:2015-08-19 18:27:01

标签: c# path getfiles

我试图获取目录中的所有文件,但我希望它们与数字相关联。现在,我有这个:

string[] ficheiro = Directory.GetFiles(@"C:\Users\David\Documents\Jogos\Jogos de emuladores\Roms GB\", "*.gba");
{
     Console.WriteLine ("F1" + " - " + Path.GetFileNameWithoutExtension (ficheiro[0]));
}
Console.ReadKey ();

当我达到10个文件时,我将有一个快捷方式来翻页以获取更多文件(每页10个)。我将手动列出所有文件。像这样:

Console.WriteLine ("F2" + " - " + Path.GetFileNameWithoutExtension (ficheiro[1]));

Console.WriteLine ("F3" + " - " + Path.GetFileNameWithoutExtension (ficheiro[2]));

有更好的方法吗?

3 个答案:

答案 0 :(得分:0)

您需要使用循环。你无法“手工”完成所有这些操作,因为你不一定知道有多少。

var files = Directory.GetFiles(@"C:\Your\Directory\Path", "*.gba");
var count = 0;

foreach (var file in files)
{
    if (count % 10 == 0 && count != 0)
    {
        Console.ReadLine();
    }

    count++;

    Console.WriteLine("F{0} - {1}", count, Path.GetFileNameWithoutExtension(file));
}
Console.ReadLine();

答案 1 :(得分:0)

您可以使用for循环迭代数组:

string[] ficheiros = Directory.GetFiles(@"C:\Users\David\Documents\Jogos\Jogos de emuladores\Roms GB\", "*.gba");
for (int i = 0; i < ficheiros.Length; i++)
{
    Console.WriteLine("F{0} - {1}", i + 1, Path.GetFileNameWithoutExtension(ficheiros[i]));
}
Console.ReadKey();

关键是识别重复部分并从中提取模式:

//only these changed V                                                       V
Console.WriteLine ("F2" + " - " + Path.GetFileNameWithoutExtension (ficheiro[1]));
Console.WriteLine ("F3" + " - " + Path.GetFileNameWithoutExtension (ficheiro[2]));

// just replace them and put it inside an appropriate loop, in this case a for-loop
for(int i = 0; i < ficheiro.Length; i++)
    Console.WriteLine ("F" + (i+1) + " - " + Path.GetFileNameWithoutExtension (ficheiro[i]));

答案 2 :(得分:0)

        int i = 0;
        var ficheiro = from s in Directory.GetFiles(@"C:\temp\", "*.*")
                       select ("F"+ i++  + "-" + s);