Reputation: 138
I have one directory contain all the tif formate file ,near about 30 file with the name like that B_1 ,B_2...upto B_15 and F_1 ,F_2...upto F_1. when i am getting file from getfile method.
Dim di As New IO.DirectoryInfo("c:\ABC\")
Dim diar1 As IO.FileInfo() = di.GetFiles()
But while retriving using for each loop i am getting the result like B_1,B_10,B_11,B_12,B_13,B_14,B_15,B_2,B_3...upto B_9 same like F_1,F_10,F_11,F_12,F_13,F_14,F_15,F_2,F_3...upto F_9
But problem is that I want in pattern like B_1,B_2,B_3,B_4.....B_9,B_10,B_11......B_15 and then F_1,F_2,F_3,F_4.....F_9,F_10,F_11......F_15
Actually My task is getting all the file from directory and join all the tiff file file like F_1,B_1,F_2,B_2...F_9,B_9,F_10,B_10,F_11,B_11,....F_15,B_15
I have achieved everthing all means join tiff and but file start with B and F i am storing in respective arrayList but due to comming file in B_,B_10..so on thats why i am getting Problem...
Plz help me...
Upvotes: 1
Views: 2070
Reputation: 43743
The simplest solution is to create a method that returns a sort key as a string, for instance, in your situation, something like this should suffice:
Public Function GetFileInfoSortKey(fi As FileInfo) As String
Dim parts() As String = fi.Name.Split("_"c)
Dim sortKey As String = Nothing
If parts.Length = 2 Then
sortKey = parts(1).PadLeft(10) & parts(0)
Else
sortKey = fi.Name
End If
Return sortKey
End Function
Then, you can use that method to easily sort the array of FileInfo
objects, like this:
Array.Sort(diar1, Function(x, y) GetFileInfoSortKey(x).CompareTo(GetFileInfoSortKey(y)))
If you don't care about keeping it as an array, you may want to use the OrderBy
extension method provided by LINQ:
Dim diar1 As IEnumerable(Of FileInfo) = di.GetFiles().OrderBy(Of String)(AddressOf GetFileInfoSortKey)
Alternatively, if you are using an older version of Visual Studio which does not support lambda expressions, you can do it by creating a separate comparer method, like this:
Public Function FileInfoComparer(x As FileInfo, y As FileInfo) As Integer
Return GetFileInfoSortKey(x).CompareTo(GetFileInfoSortKey(y))
End Function
Then you could call Array.Sort
using that comparer method, like this:
Array.Sort(diar1, AddressOf FileInfoComparer)
Upvotes: 1