Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
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?

C#
string[] fileNames = Directory.GetFiles("Spaceman");
Array.Sort(fileNames, StringComparer.InvariantCulture);
foreach (string files in fileNames)
{
    listBox2.Items.Add(files);
}
Posted
Updated 27-Feb-15 1:51am
v3

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
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)
C#
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
C#
var fileNames = Directory.GetFiles("Spaceman").OrderBy(formatFileNumberForSort);
foreach(var s in fileNames)
    Console.WriteLine("{0}", s);
which produces results of
Spaceman\1
Spaceman\2
Spaceman\10
Spaceman\11
Spaceman\20
Spaceman\21
As requested here is my entire code ... created a new Windows Forms application and stuck a button on the default form.
C#
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;
        }
    }
}
 
Share this answer
 
v3
Comments
Avenger1 27-Feb-15 9:36am    
it didn't work in vs 2013
CHill60 27-Feb-15 10:38am    
I tested this in VS2013 - what do you mean by "didn't work" ?
Avenger1 27-Feb-15 9:48am    
please see these 2 image of my program to see my problem, the first is for 100 image
http://upload7.ir/uploads//1af97ab4a609f7dc76b8dad42236f1ad2a9722d8.jpg

and this second link is for 1000 image
http://upload7.ir/uploads//27a25c8113166567aa0ef5ba5db522599e036cd0.jpg
i want it sort like this
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,...,1000
CHill60 27-Feb-15 10:40am    
I've just tested my code again and it definitely produces the order correctly.
Avenger1 27-Feb-15 10:54am    
so why for me its not working correct!
can you upload your project for me, please
With Respect
I have tested this and works fine.

C#
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;}
        }
    }

}
 
Share this answer
 
v4
Comments
Avenger1 27-Feb-15 7:54am    
i want array string not array file info
John C Rayan 27-Feb-15 7:57am    
Check now.
Avenger1 27-Feb-15 9:51am    
it didn't work
please see these 2 image of my program to see my problem, the first is for 100 image
http://upload7.ir/uploads//1af97ab4a609f7dc76b8dad42236f1ad2a9722d8.jpg

and this second link is for 1000 image
http://upload7.ir/uploads//27a25c8113166567aa0ef5ba5db522599e036cd0.jpg
John C Rayan 27-Feb-15 10:08am    
Are all of your files numeric only? no string names at all? can you confirm
John C Rayan 27-Feb-15 10:22am    
Check again my solution. I tested it and worked fine. Hope this solves your problem.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900