Search code examples
vb.netlinqdirectoryinfo

Get only those files in a directory whose name does not start with a certain string


I currently have this code:

    Dim FolderInfo As IO.DirectoryInfo = New IO.DirectoryInfo("C:\Scratch")

    For Each FInfo As IO.FileInfo In FolderInfo.GetFiles("*.xlsx")

        MessageBox.Show(FInfo.ToString())
    Next FInfo

Obviously this will get all the files that match the pattern "*.xlsx" - but I am NOT interested in any files that start with "old" - so of course within the For Next, I could do something like if If Not FInfo.Name.StartsWith("old") Then ... and do what I need to do, but I was wondering if there is any way to tell the GetFiles to only get files that "don't start with "old" and end in *.xlsx" ?

I've seen examples in C# that I believe use LINQ - so after the GetFiles there is stuff like ".Where(f => !(f.FullName.StartsWith("old")))" but not sure what ( if there is one ) the equivilant would be for VB.NET ?

Cheers,

Chris.


Solution

  • The syntax is a bit more verbose, but Where works as well in VB

    For Each FInfo As IO.FileInfo In FolderInfo.GetFiles("*.xlsx").
        Where(Function(x) Not x.Name.StartsWith("old"))
    
        MessageBox.Show(FInfo.ToString())
    Next FInfo
    

    I would also add a StringComparison.CurrentCultureIgnoreCase to remove also files that starts with "Old" or "OLD" and so on

    For Each FInfo As IO.FileInfo In FolderInfo.GetFiles("*.xlsx").
        Where(Function(x) Not x.Name.StartsWith("old", StringComparisong.CurrentCultureIgnoreCase))
    
        MessageBox.Show(FInfo.ToString())
    Next FInfo
    

    By the way, you should use the property Name instead of FullName. FullName returns also the path to the file and, obviously, this path doesn't start with "old".