D_Bester D_Bester - 6 months ago 25
Vb.net Question

Get Longest Name

I need the directory with the longest name. In the RootDir there may be several directories with names starting with "8000". I want the DirectoryInfo of the one with the longest name.

Dim pCustID As String = "8000"
Dim RootDir As New DirectoryInfo(CustPdfPath)
Dim dirs() As DirectoryInfo
dirs = Array.FindAll(RootDir.GetDirectories, Function(x) x.Name.StartsWith(pCustID))
Dim myDir As DirectoryInfo = Array.Sort(RootDir.GetDirectories, _
Function(x As DirectoryInfo, y As DirectoryInfo) _
x.Name.Length > y.Name.Length).firstordefault


Of course I'm getting: "Expressions does not produce a value". How do I fix the last line to sort by length (longest first) and take the first (longest) one.

Answer

Let's try this (without using a DirectoryInfo)

Dim pCustID As String = "8000"
Dim RootDir As String = CustPdfPath
Dim longest = Directory.GetDirectories(RootDir) _
              .Where(Function(x) Path.GetFileName(x).StartsWith(RootDir & "\" & pCustID)) _ 
              .OrderByDescending(Function(x) x.Length) _ 
              .FirstOrDefault()

or with a DirectoryInfo

Dim pCustID As String = "8000"
Dim RootDir As New DirectoryInfo(CustPdfPath)    
Dim longest = di.GetDirectories() _ 
                .Where(Function(x) x.Name.StartsWith(pCustID)) _ 
                .OrderByDescending(Function(x) x.Name.Length) _ 
                .FirstOrDefault()
Comments