1

I need to take all file in particular directory and store them in fileinfo array and sort them alphanumerically.

code snippet

        string dir = @"C:\tem";
        DirectoryInfo directory = new DirectoryInfo(dir);

        if (directory != null)
        {
            FileInfo[] files = directory.GetFiles("*.bmp");


            if (files.Length > 0)
            {
                Console.WriteLine("Files:");
                foreach (FileInfo subFile in files)
                {
                    Console.WriteLine("   " + subFile.Name + " (" + subFile.Length + " bytes)");
                }
            }
        }`

currently i am getting output

test_1.bmp test_11.bmp test_2.bmp

but i want the output like

test_1.bmp,test_2.bmp,test_11.bmp

Thanks

Rezoan
  • 1,745
  • 22
  • 51
RamKumar
  • 55
  • 5

2 Answers2

0

You can use LINQ for that:

if (directory != null)
{
      FileInfo[] files = directory.GetFiles("*.bmp");

      files.Select(f => f.Name).ToList().
          OrderBy(x=> Int32.Parse(x.Substring(x.IndexOf('_') + 1, x.IndexOf('.') - x.IndexOf('_') - 1))).
          ToList().ForEach(s => Console.WriteLine(s));
}

The output is:

test_1.bmp 
test_2.bmp 
test_11.bmp

UPDATE:

// Store as FileInfo array
FileInfo[] sortedFiles = files.OrderBy(x => Int32.Parse(x.Name.Substring(x.Name.IndexOf('_') + 1, x.Name.IndexOf('.') - x.Name.IndexOf('_') - 1))).
           ToArray();

// Do whatever you want
foreach (FileInfo item in sortedFiles)
{
    Console.WriteLine(string.Format("FullPath -> {0}", item.FullName));
}
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
  • thanks for quick reply. Actually i need to pass them and will be used for various purpose such as getting file property ,full path and last index of file. Is it possible to store sorted file info array back to same or diffrent fileinfo array. – RamKumar Oct 13 '13 at 07:05
0
public static void Main()
{
    string dir = @"C:\tem";
    var directory = new DirectoryInfo(dir);

    FileInfo[] files = directory.GetFiles("*.bmp");

   var sortedFiles=files.ToDictionary(k=>GetIntValueFromString(k.Name),v=>v).OrderBy(entry=>entry.Key);

   foreach (var file in sortedFiles)
    {
        Console.WriteLine(file.Value.Name);
    }
    Console.Read();


}

static int GetIntValueFromString(string input)
{
    var result = 0;
    var intString = Regex.Replace(input, "[^0-9]+", string.Empty);
    Int32.TryParse(intString, out result);

    return result;
}
Sameer
  • 3,124
  • 5
  • 30
  • 57
  • look like this will be used for sorting only string array. I need to sort Fileinfo[] and store them in new Fileinfo1[]. – RamKumar Oct 13 '13 at 07:07
  • You can just easily use the same solution to get the sorted file list with minor modification. But the essence remains the same. Please see the update. – Sameer Oct 13 '13 at 09:46