1

我需要获取特定目录中的所有文件并将它们存储在 fileinfo 数组中并按字母数字对其进行排序。

代码片段

        string dir = @"C:\tem";
        DirectoryInfo directory = new DirectoryInfo(dir);

        if (directory != null)
        {
            FileInfo[] files = directory.GetFiles("*.bmp");


            if (files.Length > 0)
            {
                Console.WriteLine("Files:");
                foreach (FileInfo subFile in files)
                {
                    Console.WriteLine("   " + subFile.Name + " (" + subFile.Length + " bytes)");
                }
            }
        }`

目前我正在获得输出

test_1.bmp test_11.bmp test_2.bmp

但我想要像这样的输出

test_1.bmp,test_2.bmp,test_11.bmp

谢谢

4

2 回答 2

0

您可以为此使用 LINQ:

if (directory != null)
{
      FileInfo[] files = directory.GetFiles("*.bmp");

      files.Select(f => f.Name).ToList().
          OrderBy(x=> Int32.Parse(x.Substring(x.IndexOf('_') + 1, x.IndexOf('.') - x.IndexOf('_') - 1))).
          ToList().ForEach(s => Console.WriteLine(s));
}

输出是:

test_1.bmp 
test_2.bmp 
test_11.bmp

更新

// Store as FileInfo array
FileInfo[] sortedFiles = files.OrderBy(x => Int32.Parse(x.Name.Substring(x.Name.IndexOf('_') + 1, x.Name.IndexOf('.') - x.Name.IndexOf('_') - 1))).
           ToArray();

// Do whatever you want
foreach (FileInfo item in sortedFiles)
{
    Console.WriteLine(string.Format("FullPath -> {0}", item.FullName));
}
于 2013-10-13T06:20:02.203 回答
0
public static void Main()
{
    string dir = @"C:\tem";
    var directory = new DirectoryInfo(dir);

    FileInfo[] files = directory.GetFiles("*.bmp");

   var sortedFiles=files.ToDictionary(k=>GetIntValueFromString(k.Name),v=>v).OrderBy(entry=>entry.Key);

   foreach (var file in sortedFiles)
    {
        Console.WriteLine(file.Value.Name);
    }
    Console.Read();


}

static int GetIntValueFromString(string input)
{
    var result = 0;
    var intString = Regex.Replace(input, "[^0-9]+", string.Empty);
    Int32.TryParse(intString, out result);

    return result;
}
于 2013-10-13T06:36:26.913 回答