Saravanan
Saravanan

Reputation: 11592

How to get the files in numeric order from the specified directory in c#?

I have to retrieve list of file names from the specific directory using numeric order.Actually file names are combination of strings and numeric values but end with numeric values.

For example : page_1.png,page_2.png,page3.png...,page10.png,page_11.png,page_12.png...

my c# code is below :

string filePath="D:\\vs-2010projects\\delete_sample\\delete_sample\\myimages\\";
string[] filePaths = Directory.GetFiles(filePath, "*.png");

It retrieved in the following format:

page_1.png
page_10.png
page_11.png
page_12.png
page_2.png...

I am expecting to retrieve the list ordered like this:

page_1.png
page_2.png
page_3.png
[...]
page_10.png
page_11.png
page_12.png

Upvotes: 2

Views: 4449

Answers (5)

S.N
S.N

Reputation: 5140

You can try following code, which sort your file names based on the numeric values. Keep in mind, this logic works based on some conventions such as the availability of '_'. You are free to modify the code to add more defensive approach save you from any business case.

var vv = new DirectoryInfo(@"C:\Image").GetFileSystemInfos("*.bmp").OrderBy(fs=>int.Parse(fs.Name.Split('_')[1].Substring(0, fs.Name.Split('_')[1].Length - fs.Extension.Length)));

Upvotes: 2

Soner Gönül
Soner Gönül

Reputation: 98740

Maybe this?

string[] filePaths = Directory.GetFiles(filePath, "*.png").OrderBy(n => n);

EDIT: As Marcelo pointed, I belive you can get get all file names you can get their numerical part with a regex, than you can sort them including their file names.

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 185862

Ian Griffiths has a natural sort for C#. It makes no assumptions about where the numbers appear, and even correctly sorts filenames with multiple numeric components, such as app-1.0.2, app-1.0.11.

Upvotes: 5

Kaveh Shahbazian
Kaveh Shahbazian

Reputation: 13513

This code would do that:

var dir = @"C:\Pictures";
var sorted = (from fn in Directory.GetFiles(dir)
                let m = Regex.Match(fn, @"(?<order>\d+)")
                where m.Success
                let n = int.Parse(m.Groups["order"].Value)
                orderby n
                select fn).ToList();

foreach (var fn in sorted) Console.WriteLine(fn);

It also filters out those files that has not a number in their names.

You may want to change the regex pattern to match more specific name structures for file names.

Upvotes: 0

h.meknassi
h.meknassi

Reputation: 189

First you can extract the number:

static int ExtractNumber(string text)
{
    Match match = Regex.Match(text, @"_(\d+)\.(png)");
    if (match == null)
    {
        return 0;
    }

    int value;
    if (!int.TryParse(match.Value, out value))
    {
        return 0;
    }

    return value;
}

Then you could sort your list using:

list.Sort((x, y) => ExtractNumber(x).CompareTo(ExtractNumber(y)));

Upvotes: 2

Related Questions