繁体   English   中英

升序排列文件

[英]Sort files in ascending order

我有一个将pdf转换为tif图像文件的项目。 并且输出文件以表格编号。 file1,file2,file3 ....... file20。 当我执行下面的代码以获取文件时,它们如下所示排列在列表中,这是不正确的。 任何想法如何解决这个问题?

FileInfo[] finfos = di.GetFiles("*.*");

finfos[0]=file1

finfos[1]=file10

finfos[2]=file11

finfos[3]=file12

....
...................

finfos[4]=file19

finfos[5]=file2

finfos[6]=file20

finfos[7]=file3

finfos[7]=file4

如果所有文件都命名为mypic<number>.tif并且目录中没有名称格式不同的文件,请尝试以下操作:

        FileInfo[] orderedFI = finfos
            .OrderBy(fi => 
                // This will convert string representation of a number into actual integer
                int.Parse(
                    // this will extract the number from the filename
                    Regex.Match(Path.GetFileNameWithoutExtension(fi.Name), @"(\d+)").Groups[1].Value
                    ))
            .ToArray();

如果按顺序创建它们,则按创建日期对它们进行排序。

这是使用列表解决问题的方法

class Program
{
    private static int CompareWithNumbers(FileInfo x, FileInfo y)
    {
        if (x == null)
        {
            if (y == null)
            {
                // If x is null and y is null, they're 
                // equal.  
                return 0;
            }
            else
            {
                // If x is null and y is not null, y 
                // is greater.  
                return -1;
            }
        }
        else
        {
            // If x is not null... 
            // 
            if (y == null)
            // ...and y is null, x is greater.
            {
                return 1;
            }
            else
            {

                int retval = x.CreationTime<y.CreationTime?-1:1;
                return retval;          

            }
        }
    }
    static void Main(string[] args)
    {
        DirectoryInfo di = new DirectoryInfo("d:\\temp");
        List<FileInfo> finfos = new List<FileInfo>();
        finfos.AddRange(di.GetFiles("*"));
        finfos.Sort(CompareWithNumbers);

        //you can do what ever you want
    }
}

前导零可能是您的解决方案。 从您的描述中还不清楚您是否控制生成文件的代码。 如果不是,则可以使用一种方法来匹配file1,... file9(即正则表达式或文件名长度)并将其重命名。 如果控制代码,则使用格式化程序将数字转换为带有前导零的字符串(即2位数字{0:00})。

编辑:

要获得以下草稿示例的指导,请执行以下操作:

假设您在执行目录中具有以下文件:file1.txt,file2.txt,file10.txt和file20.txt

foreach (string fn in System.IO.Directory.GetFiles(".", "file*.*"))
  if (System.Text.RegularExpressions.Regex.IsMatch(fn, @"file\d.txt"))
    System.IO.File.Move(fn, fn.Replace("file", "file0"));

上面的代码将把file1.txt重命名为file01.txt,将file2.txt重命名为file02.txt。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM