C# Sorting an Array of files

Experts,
I have been working on small C# project that requires me to write to file, the contents of a given folder. However, the problem I have is the order that the files are written. I need to sort the array, so that the files are ordered by the number prior to the file extension.

Example File Name Format

Test_File_Name_01.txt
Test_File_Name_02.txt
Test_File_Name_03.txt
etc...

File name can be any length.


I have looked into using ICompare but not sure I how to use it.

Can anyone throw any light onto this subject?  

Below is what I have written thus far.
string filePath = ConfigurationManager.AppSettings["FileListPath"].ToString;

string [] currentDirectoryFileList = Directory.GetFiles(filepath); 

Array.Sort(currentDirectoryFileList)

using(StreamWriter sw = File.CreateText("C:/Test.txt")
{
   foreach(string fileName in currentDirectoryFileList)
   {
     sw.WriteLine(fileName); 
   }
   sw.Close(); 
}

Open in new window

PlanmasterAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Carl TawnSystems and Integration DeveloperCommented:
Is there any consistency to your filenames (i.e. do they always end with underscore plus a number)? And what version of .Net are you targetting?
0
Göran AnderssonCommented:
You can use a regular expression to find the digits before the extension, and the OrderBy extension to sort the file names.

Note: When you create the StreamWriter in the using clause it will automatically be disposed, so you don't need to close it.
string filePath = ConfigurationManager.AppSettings["FileListPath"].ToString();

string [] currentDirectoryFileList = Directory.GetFiles(filePath); 

using (StreamWriter sw = File.CreateText("C:/Test.txt")) {
  foreach(string fileName in currentDirectoryFileList.OrderBy(f => Regex.Match(f, @"(\d*)\.").Groups[1].Value)) {
    sw.WriteLine(fileName); 
  }
}

Open in new window

0
Vel EousResearch & Development ManagerCommented:
Take a look at the following example.
private void button1_Click(object sender, EventArgs e)
{
    // Create a connection to the current working directory
    // This can obviously be replaced with any valid directory path
    DirectoryInfo di = new DirectoryInfo(Directory.GetCurrentDirectory());
    // Instantiate a collection of strings for holding the names of the files
    // This could be replaced with a collection of FileInfo types if you wanted
    // a little more information other than just filenames
    List<string> files = new List<string>();
    // Iterate through all the files found in the working directory
    // You can add filters to this so that only files with a particular extension
    // are read.  You can also do di.GetDirectories() if you wanted any directories
    // that may be in the working directory too
    foreach (FileInfo f in di.GetFiles("*.*"))
    {
        // Add the name of the file to the collection
        files.Add(f.Name);
    }
    // Sort the files
    files.Sort();
    // Iterate through the names in the collection
    foreach (string filename in files)
    {
        // Maniupulate the filenames however you see fit
        this.richTextBox1.AppendText(filename + Environment.NewLine);
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
0
PlanmasterAuthor Commented:
Thank you all for your help. All the solutions were helpful and I used ideas them all.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.