Sort files by name c #

0

I have several files like this:

- C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04170405_TR_CREATE_TABLE_BMTApprovalGroupExam.sql
- C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04170405_TR_CREATE_PROC_BMSPInsertNewApprovalRequest2.sql
- C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04170405_TR_CREATE_PROC_BMSPUpdateApprovalRequest2.sql 
- C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04170405_TR_CREATE_PROC_BMSPInsertNewApprovalGroupExam.sql

I need to sort the files like this in C #:

- C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04170405_TR_CREATE_TABLE_BMTApprovalGroupExam.sql
- C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04170405_TR_CREATE_PROC_BMSPInsertNewApprovalGroupExam.sql
- C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04170405_TR_CREATE_PROC_BMSPInsertNewApprovalRequest2.sql
- C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04170405_TR_CREATE_PROC_BMSPUpdateApprovalRequest2.sql 

I did so:

string[] sqlFiles = Directory.GetFiles(path, "*.sql", SearchOption.TopDirectoryOnly);
foreach (string file in sqlFiles.OrderBy(file => file)) { }

But it's not working. It is performing by the first step I have.

    
asked by anonymous 29.05.2017 / 14:00

2 answers

5

Following the response from @jbueno, you can use the Path.GetFileName to return only the filename, and proceed with the ordering with .Split('_')[0] , to use only the numbers.

See the example below:

var sqlFiles = new[] { @" C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04170405_TR_CREATE_TABLE_BMTApprovalGroupExam.sql",
                       @" C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04‌0170405_TR_CREATE_PROC_BMSPInsertNewApprovalRequest2.sql",
                       @" C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04‌0170405_TR_CREATE_PROC_BMSPUpdateApprovalRequest2.sql",
                       @" C:\ByMe\SOLUTIONS\Dictation1\Database\Updates1717_04‌0170405_TR_CREATE_PROC_BMSPInsertNewApprovalGroupExam.sql" };

foreach (string file in sqlFiles.OrderBy(file => Convert.ToInt32(Path.GetFileName(file).Split('_')[0])))

{
    Console.WriteLine(file);
}

See working in .NetFiddle.

    
29.05.2017 / 14:39
0

To help those who need it, the answer to the already resolved question is as follows:

    string[] sqlFilesLocation = Directory.GetFiles(path, "*.sql", SearchOption.TopDirectoryOnly);
 foreach (string file in sqlFilesLocation.OrderBy(file => Convert.ToInt32(Path.GetFileName(file).Split('_')[0])))
    
26.06.2017 / 16:27