如何在c#中对文件名进行排序 [英] How To Sort File Names In c#

查看:159
本文介绍了如何在c#中对文件名进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文件夹中获取所有文件,但文件未排序。

文件'名称是数字,例如1,2,3,4,...,1000。

如何对这些文件名进行排序?



I want to get all files from a folder but files are not sorted.
The file' names are number for example 1,2,3,4,...,1000.
How to sort this file names?

string[] fileNames = Directory.GetFiles("Spaceman");
Array.Sort(fileNames, StringComparer.InvariantCulture);
foreach (string files in fileNames)
{
    listBox2.Items.Add(files);
}

推荐答案

我认为其他前2张海报错过了什么是你明确说文件名是数字的。



所以,如果你的文件名为
I think what the other first 2 posters have missed is that you explicitly said that the filenames are numeric.

So if you have filenames of
1
2
10
11
20
21

到目前为止提供的解决方案将按以下顺序显示该列表

the solutions offered so far will present that list in the following order

1
10
11
2
20
21

我假设您需要我最初提交的订单。

为此,您需要从文件名中删除路径并在排序之前将其转换为数字。我正在继续使用GetFiles,因为我认为DirectoryInfo对于我们想要的东西来说有点重量级。



首先我创建了一个将剥离的静态函数foldername并将文件名转换为整数(如果可能)

I'm assuming you want the order as I originally presented it.
To do that you need to strip the path off the filenames and convert it to a number before sorting it. I'm continuing to use GetFiles as you have done because I think DirectoryInfo is a little heavyweight for what we want.

First I created a static function that will strip off the foldername and convert the filename to an integer (if possible)

private static string formatFileNumberForSort(string inVal)
{
    int o;
    if (int.TryParse(Path.GetFileName(inVal), out o))
    {
        Console.WriteLine(string.Format("{0:0000000000}", o));
        return string.Format("{0:0000000000}", o);
    }
    else
        return inVal;
}

然后我使用这个函数,像这样

I then use that function like this

var fileNames = Directory.GetFiles("Spaceman").OrderBy(formatFileNumberForSort);
foreach(var s in fileNames)
    Console.WriteLine("{0}", s);

产生

Spaceman\1
Spaceman\2
Spaceman\10
Spaceman\11
Spaceman\20
Spaceman\21

这里要求的是我的整个代码...创建了一个新的Windows窗体应用程序并在默认窗体上粘贴了一个按钮。

As requested here is my entire code ... created a new Windows Forms application and stuck a button on the default form.

using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // I have files called 1, 2, 10, 11, 20, 21 in my temp\test2 folder
            var fileNames = Directory.GetFiles("c:\\temp\\test2").OrderBy(formatFileNumberForSort);
            foreach(var s in fileNames)
                Console.WriteLine("{0}", s);
        }

        private static string formatFileNumberForSort(string inVal)
        {
            int o;
            if (int.TryParse(Path.GetFileName(inVal), out o))
            {
                Console.WriteLine(string.Format("{0:0000000000}", o));
                return string.Format("{0:0000000000}", o);
            }
            else
                return inVal;
        }
    }
}


我测试了这个并且工作正常。



I have tested this and works fine.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {


        DirectoryInfo info = new DirectoryInfo("c:\\Snowman");
        string[] fileNames = info.GetFiles().OrderBy(p => Path.GetFileNameWithoutExtension(p.Name),new ComparerN()  )
                                 .Select(fi => fi.Name).ToArray();




        }
    }


    public class ComparerN : IComparer<string>
    {
        public int Compare(string sf, string ss)
        {
            if (IsNumer(sf) && IsNumer(ss))
            {
                if (Convert.ToInt32(sf) > Convert.ToInt32(ss))
                {
                    return 1;
                }
                if (Convert.ToInt32(sf) < Convert.ToInt32(ss))
                {
                    return -1;
                }
                if (Convert.ToInt32(sf) == Convert.ToInt32(ss))
                {
                    return 0;
                }
            }

            if (IsNumer(sf) && !IsNumer(ss))
                return -1;

            if (!IsNumer(sf) && IsNumer(ss))
                return 1;

            return string.Compare(sf, ss, true);
        }

        public static bool IsNumer(object v)
        {

            try
            {
                int it = Convert.ToInt32(v.ToString());
                return true;
            }
            catch (FormatException){return false;}
        }
    }

}


这篇关于如何在c#中对文件名进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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