How to represent testfile name using regular expression in VB

Viewed 35

Newbie here. I have the following code in VB for reading csv file. Filename includes current date so it changes daily. How do I represent the filename using regular expression so it will read any csv file? Thanks

Dim objReader = New IO.StreamReader("\\FolderA\FolderB\SEBCTS20220831.csv")

I have tried -

        objReader = New IO.StreamReader("\\FolderA\FolderB\^SEBCTS\w\w\w\w\w\w\w\w\.csv$")
    'objReader = New IO.StreamReader("\\FolderA\FolderB\^\w\w\w\w\w\w\w\w\w\w\w\w\w\w\.csv$")

But I get an error -

Error: Could not find a part of the path '\FolderA\FolderB^SEBCTS\w\w\w\w\w\w\w\w.csv$'.

1 Answers

Why you need regex, use Date.TryParseExact and Path.GetFileNameWithoutExtension:

Dim file = "\\FolderA\FolderB\SEBCTS20220831.csv"
Dim fileName = Path.GetFileNameWithoutExtension(file)
Dim format = "yyyyMMdd"
Dim possibleDate = If(fileName.Length >= format.Length, fileName.Substring(fileName.Length - format.Length), Nothing)
Dim parsedDate As Date
Dim isValidFile = Date.TryParseExact(possibleDate, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, parsedDate)

If you not even want to ensure that the last digits of the file-name is a valid date but also today:

isValidFile = isValidFile AndAlso parsedDate.Date = Date.Today
Related