Click here to Skip to main content
15,907,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an application that lists files within a directory. The files have various lengths but they have a string I wish to sort them by in the middle of the file name.

Here is an example of the file names, the string I want to sort by is the B1A32 and B2A39 section.

thisisafilestringB1A32continuedstring.dat
thisisanotherfilestringB2A39continuedotherstring.dat

I have been using the following code to sort by date and name:

VB
Dim files As Linq.IOrderedEnumerable(Of IO.FileInfo)

files = New DirectoryInfo(My.Settings("Store" & clickedTbNumber)).GetFiles().OrderBy(Function(f As FileInfo) f.CreationTime)

files = New DirectoryInfo(My.Settings("Store" & clickedTbNumber)).GetFiles().OrderBy(Function(f As FileInfo) f.Name)


How can I sort the files by the B1A32 and B2A39 strings in the middle of the string? I am using Visual Basic 2010 Express.
Posted

1 solution

Assuming you can better define the actual pattern you want to use, something like this:
I'm going to assume the pattern is
Uppercase letter B
followed by 1 or more digits
followed by uppercase letter A
followed by 1 or more digits.

And that you can guarantee it occurs only once in any filename.
VB
Function SortMidName (name as String) As String
  Dim rgx As New Regex("(B\d+A\d+)")
  Dim match As Match = rgx.Match(name)
  If match.Success Then
    Return match.Groups(1).Value
  End If
  Return String.Empty  ' Or fail in some other way
End Function


files = New DirectoryInfo(My.Settings("Store" && clickedTbNumber)).GetFiles().OrderBy(Function(f As FileInfo) SortMidName(f.Name))

Take the above with a grain of salt... my VB is pretty weak (my c# on the other hand!)
 
Share this answer
 
Comments
Lambda09a 14-Feb-14 3:24am    
Beautiful! Thank you very much. I thought it would come down to RegEx but wasn't sure how to implement it. Will look into it in more detail. Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900