从c#中的目录中排序文件 [英] sort the files from directory in c#

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

问题描述


为什么你关闭了我的问题???????????????? b $ b谢谢Alexandrovich Kryukov请再次发送你的答案,我想做你做的事情说,但他们关闭了我的问题,现在我不能这样做

****************

im使用此代码从目录获取所有文件,我的文件名是数字,但它随机获取文件,但我希望它采取这样排序的文件

  1  
2
3
4
5
6
7
8
9
10
11
12
13
14



1000



这是我的代码

  string  [] fileNames = Directory.GetFiles( 太空人); 
foreach string s in fileNames)
{
listBox2.Items.Add(s.Replace( 。jpg )。替换( @ Spaceman \ ));
}



我的代码给我这样的文件

  1  
10
11
12
13
14
15
16
17
18
19
2
20




它必须是string []而不是var

请帮我修复它

尊重

解决方案

尝试:

  string  [] files = Directory.GetFiles(path).OrderBy(f = >   int  .Parse(Path.GetFileNameWithoutExtension(f)))。ToArray(); 


问题是文件名是字符串而不是数字。 ..

在字符串排序中,10出现在2之前...

在win表单列表框中有一个Sort方法,可用于特定于用户的排序:https://msdn.microsoft.com/en- us / library / system.windows.forms.listbox.sort%28v = vs.110%29.aspx [ ^ ]

在网络表单中,您需要先排序列表,然后将其添加到列表框中,如下所示:

< pre lang =c#>列表< listitem> sortedList = new List< listitem>();
比较compareMethod = new 比较(compareItems); // int compareItems(ListItem li1,ListItem li2){//在此进行比较}

sortedList.Sort(compareMethod);
listBox.Items.AddRange(sortedList.ToArray());



(这几乎适用于任何类型的列表框......)


的确,我已经解释了这些想法,但现在我将它与现有的解决方案2结合起来:

 使用 System.IO; 
使用 System.Linq;

// ...

< span class =code-keyword> string [] files = Directory.GetFiles(path).OrderBy(f = > {
int number;
if int .TryParse(Path.GetFileNameWithoutExtension(f), out number))
return number ;
else
return -1; // 或其他一些后备值
})。ToArray();



此解决方案为名称无法解析为整数的文件提供了一些回退顺序。没有它,解决方案2不太令人满意,因为在这种情况下 int.Parse 将在列出所有文件之前抛出异常。



此解决方案的一个问题是非整数文件的顺序未定义。要提供更确定的输出,您可以对所有文件进行排序。例如:

 使用 System.IO; 
使用 System.Linq;
使用 StringList = System.Collections.Generic.List< string> ;;

// ...

< span class =code-keyword> string [] files = Directory.GetFiles(path);
StringList list = new StringList();
list.AddRange(Directory.GetFiles(path));
list.Sort( new System.Comparison< string>((left,right)= > {
string noExtLeft = Path.GetFileNameWithoutExtension(left);
string noExtRight = Path.GetFileNameWithoutExtension(右);
ulong nleft,nright;
if ulong .TryParse(noExtLeft, out nleft)
&&& ulong .TryParse(noExtRight, out nright)){
if (nleft == nright) return 0 ;
else if (nleft > nright)返回 +1;
else return -1;
} else
return left.CompareTo(right);
}));



我可能在签名和比较顺序上犯了错误;请检查一下,以确保这是数字顺序,而不是反向数字顺序,并且回退为您提供了对后备比较中字母数字顺序的正确比较(对于非数字):https://msdn.microsoft.com/en-us/library/tfakywbh%28v=vs.110%29 .aspx [ ^ ]。



另请参阅: https://msdn.microsoft.com/en-us/library/w56d4y5z%28v=vs.110%29.aspx [ ^ ]。



-SA


hi why you closed my question??????????????
Sergey Alexandrovich Kryukov please send your answer again, i want to do what you said but they closed my question and now i can't do that
****************
i m using this code to get all files from directory and my files name are number but it get files random but i want it take files sorted like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.
.
.
1000


and this is my code

string[] fileNames = Directory.GetFiles("Spaceman");
        foreach (string s in fileNames)
        {
            listBox2.Items.Add(s.Replace(".jpg", "").Replace(@"Spaceman\", ""));
        }


and my code give me files like this

1
10
11
12
13
14
15
16
17
18
19
2
20
.
.
.


and it must be in "string[]" not "var"
please help me to fix it
With Respect

解决方案

Try:

string[] files = Directory.GetFiles(path).OrderBy(f => int.Parse(Path.GetFileNameWithoutExtension(f))).ToArray();


The problem is that file names are strings and not numbers...
In string ordering 10 comes before 2...
In win forms list box has a Sort method that can be used for user specific sort: https://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.sort%28v=vs.110%29.aspx[^]
In a web form you need the sort first the list and than you can add it to the list box like this:

List<listitem> sortedList = new List<listitem>();
Comparison compareMethod = new Comparison(compareItems); // int compareItems(ListItem li1, ListItem li2) { // do your comparsion here }

sortedList.Sort(compareMethod);
listBox.Items.AddRange(sortedList.ToArray());


(This may work for almost any kind of list boxes...)


Indeed, I already explained the ideas, but now I'll combine it with existing Solution 2:

using System.IO;
using System.Linq;

// ...

string[] files = Directory.GetFiles(path).OrderBy(f => {
    int number;
    if (int.TryParse(Path.GetFileNameWithoutExtension(f), out number))
        return number;
    else
        return -1; // or some other fallback value
}).ToArray();


This solution provides some fallback order for the files with names which cannot be parsed as integers. Not having it, Solution 2 is not quite satisfactory, because in such cases int.Parse will throw exception before all files are listed.

One problem of this solution is that the order of non-integer files is not undefined. To provide more deterministic output, you can sort all files. For example:

using System.IO;
using System.Linq;
using StringList = System.Collections.Generic.List<string>;

// ...

string[] files = Directory.GetFiles(path);
StringList list = new StringList();
list.AddRange(Directory.GetFiles(path));
list.Sort(new System.Comparison<string>((left, right) => {
    string noExtLeft = Path.GetFileNameWithoutExtension(left);
    string noExtRight = Path.GetFileNameWithoutExtension(right);
    ulong nleft, nright;
    if (ulong.TryParse(noExtLeft, out nleft)
        && ulong.TryParse(noExtRight, out nright)) {
        if (nleft == nright) return 0;
        else if (nleft > nright) return +1;
        else return -1;
    } else
        return left.CompareTo(right);
}));


I could have made a mistake in sign and order of comparison; please check it up, to make sure this is numeric order, not inverse numeric order, and the that the fallback gives you correct comparison for alphanumeric order in the fallback comparison (for non-numbers): https://msdn.microsoft.com/en-us/library/tfakywbh%28v=vs.110%29.aspx[^].

See also: https://msdn.microsoft.com/en-us/library/w56d4y5z%28v=vs.110%29.aspx[^].

—SA


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

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