排序文件的重命名的数组 [英] Sorting an array of files for rename

查看:150
本文介绍了排序文件的重命名的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近写了一个小程序,重命名一束位于6目录下的文件中。该程序遍历从列表中的每个目录,然后重命名中使用File.Move方法目录中的每个文件。该文件被重命名由1每次cart_buttons_1.png与1递增。

I've recently written a small program to rename a bunch of files located in 6 directories. The program loops through each directory from a list and then renames each file in that directory using the File.Move method. The files are renamed to cart_buttons_1.png with the 1 incrementing by 1 each time.

public static int RenameFiles(DirectoryInfo d, StreamWriter sqlStreamWriter, 
                                       int incrementer, int category, int size)
{
    FileInfo[] files = d.GetFiles("*.png");

    foreach (FileInfo fileInfo in files)
    {
        File.Move(fileInfo.FullName, d.FullName + "cart_button_" + incrementer + ".png" );
        incrementer++;
    }

    return incrementer;
}

我现在遇到的问题是,当我运行该程序不止一次运行良好,直到它击中包含100记录的文件夹。该d.Getfiles方法检索所有与100S文件第一次,引起和IOException异常,因为它正试图已重命名文件所在的文件夹中。我发现这个解决方法就是选择的所有记录中的100名,并将它们全部重命名为Z或东西,所以,它只是进行批处理它们放在一起。关于如何解决此问题的任何想法或意见。可能一些方式来GetFiles的排序,看别人是第一位。

The problem I'm encountering is when I run the program more than once it runs fine up until it hits the folder containing the 100th record. The d.Getfiles method retrieves all the files with the 100s first, causing and IOException, because the file which it is trying to rename already exists in the folder. The workaround I've found for this is just to select all the records with 100 in the filename and renaming them all to 'z' or something so that it just batches them all together. Any thoughts or ideas on how to fix this. Possibly some way to sort the GetFiles to look at the others first.

推荐答案

使用LINQ:

var sorted = files.OrderBy(fi => fi.FullName).ToArray();

请注意,上面将文本值进行排序,所以你可能要改变的数值命令:

Note that the above will sort by the textual values, so you may want to change that to order by the numeric value:

files.OrderBy(fi => int.Parse(fi.Name.Split(new []{'_','.'})[2]))

以上假设由分裂_ 的文件名和将导致与第三数组值作为数字值。

The above assumes that splitting by _ and . of a file name will result in an array with the third value being the numeric value.

这篇关于排序文件的重命名的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆