How to represent testfile name using regular expression in VB - vb.net

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$'.

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

Reading text from one file, to check other text file for matches

So I'm new to VB.NET, and I'm trying to read through 2 separate text files. File2 first & pulling a variable from it. I then want to take that variable, and check File1 to see if the string matches. Both files are relatively large, and I have to trim part of the string from the beginning, hence the multiple splits. So currently, this is what I have. But where I'm getting hung up is, how do I get it to check every line to see if it matches with the other file?
Public Function FileWriteTest()
Dim file1 = My.Computer.FileSystem.OpenTextFileReader(path)
Dim file2 = My.Computer.FileSystem.OpenTextFileReader(path)
Do Until file2.EndOfStream
Dim line = file2.ReadLine()
Dim noWhiteSpace As New String(line.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
Dim split1 = Split(noWhiteSpace, "=")
Dim splitStr = split1(0)
If splitStr.Contains(HowImSplittingText) Then
Dim parameter = Split(splitStr, "Module")
Dim finalParameter = parameter(1)
End If
'Here is where I'm not sure how to continue. I have trimmed the variable to where I would like to check with the other file.
'But i'm not sure how to continue from here.
Here are a couple of cleanup notes:
Get the lines of your first file by using IO.File.ReadAllLines (documentation)
Get the text of the second file by using IO.File.ReadAllText (documentation)
Use String.Replace (documentation) instead of Char.IsWhitespace, this is quicker and much more obvious as to what is going on
Use String.Split (documentation) instead of Split (because this is 2021 not 1994).
In terms of what you would do next, you would call String.IndexOf (documentation) on the second file's text, passing your variable value, to see if it returns a value greater than -1. If it does, then you know where at in the file the value exists.
Here is an example:
Dim file1() As String = IO.File.ReadAllLines("path to file 1")
Dim file2 As String = IO.File.ReadAllText("path to file 2")
For Each line In file1
Dim noWhiteSpace As String = line.Replace(" ", String.Empty)
Dim split1() As String = noWhiteSpace.Split("=")
If (splitStr.Length > 0) Then
Dim splitStr As String = split1(0)
If splitStr.Contains(HowImSplittingText) Then
Dim parameter() As String = splitStr.Split("Module")
If (parameter.Length > 0) Then
Dim finalParameter As String = parameter(0)
Dim index As Integer = file2.IndexOf(finalParameter)
If (index > -1) Then
' finalParameter is in file2
End If
End If
End If
End If
Next

Possible to get last modified date of folder?

I have a block of code which reads all the files in a directory, and gets the latest date from all those files. Not sure if I'm being silly, but is there a way to do the same thing but by getting the last modified date of the folders within that directory instead of the files?
Dim chkPath = "C:\CheckFolders"
Dim directory As New System.IO.DirectoryInfo(chkPath)
Dim File As System.IO.FileInfo() = directory.GetFiles()
Dim File1 As System.IO.FileInfo
Dim LastModified As String
For Each File1 In File
LastModified = System.IO.File.GetLastWriteTime(chkPath & "\" & File1.Name).ToShortDateString()
Next
MsgBox(LastModified)
Instead of hoping that the directory entries are returned in ascending date order, you should actively find the latest one. You can do that with the LINQ Max method like this:
Shared Function GetLatestFileModified(d As String) As DateTime
Dim di = New DirectoryInfo(d)
Dim latest = di.EnumerateFiles().Max(Function(i) i.LastWriteTimeUtc)
Return latest
End Function
Shared Function GetLatestDirectoryModified(d As String) As DateTime
Dim di = New DirectoryInfo(d)
Dim latest = di.EnumerateDirectories().Max(Function(i) i.LastWriteTimeUtc)
Return latest
End Function
For example,
Dim src = "C:\temp"
Console.WriteLine(GetLatestFileModified(src).ToShortDateString())
Console.WriteLine(GetLatestDirectoryModified(src).ToShortDateString())
might give
26/04/2019
10/04/2019
I have the following code in my solution.
'Check if file needs updating
Dim infoStkReader As System.IO.DirectoryInfo
infoStkReader = My.Computer.FileSystem.GetDirectoryInfo(SUI)
Dim CurrentdirectoryDate As DateTime = infoStkReader.LastWriteTime
Where SUI is the directory path.
Thanks,
Richard.

Create a text file with date and time as the filename

I'm trying to create a text file with Visual Studio in VB.Net, and I want the filename to be the current date and time.
I have this code:
Dim d As System.DateTime
DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
Dim filepath As String = d + ".txt"
If Not System.IO.File.Exists(filepath) Then
System.IO.File.Create(filepath).Dispose()
End If
But every time I use d it gives me the System.NotSupportedException error. I can only create a text file by specifying the filename. How can i fix it and make my text file's name the current date and time?
Your code fails to assign a value to the variable called d. Also, you want d to be a string, not a DateTime. Finally, the / and : characters in from your date and time are not valid in a windows filename. Either remove them or replace them with valid characters. Replace your first three lines of code with:
Dim d As String = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")
Dim filepath As String = d & ".txt"
You are trying with '/' and ':' in file name, while creating file this special characters not allowed.
Dim dateString = DateTime.Now.ToString("yyyyMMdd_HH_mm_ss")
Dim filepath As String = dateString + ".txt"
If Not System.IO.File.Exists(filepath) Then
System.IO.File.Create(filepath).Dispose()
End If

Best Way to parse File

I have a string with following format
Zone: 1 Events: 3
Zone: 2 Events: 7
i am parsing the file with following code
Dim strarr() As String
strarr = Str.Split("/n")
for i = 0 to 2
dim strarrNew() as string
strarrNew = strarr(i)Split(" ")
use value strarrNew(0)
use value strarrNew(1)
next
and i am using values directly but if their is a mistake in the string input
Zone:1Events: 3
spaces are missing than code will not work.
What would be the best way to parse file.
You can adopt this solution only if all the inputs from the file is of the same format:
For Each line As String In File.ReadAllLines("F:\sample.txt")
Dim strarrNew() As String = line.Split(":"c.ToCharArray())
Dim zone As Integer = CInt(Val(strarrNew(1)))
Dim events As Integer = CInt(Val(strarrNew(2)))
'Perform your operations
Next

VBNET Reading a specific column on a line in a text file

I have saved written a text file and it currently reads:
"first","surname","pass"
I want to read the password column so the 3rd one and define that as a variable. Its basically for a login, if pass in text file matches the entered pass (from user).
I have searched for about an hour now and no luck. Could someone guide me to a correct path.
Thanks.
Simple example of reading a small file line by line and splitting each one into fields:
' get the values from the user somehow:
Dim first As String = "James"
Dim surname As String = "Bond"
Dim pass As String = "007"
Dim validated As Boolean = False ' assume wrong until proven otherwise
' check the file:
Dim fileName As String = "c:\some folder\path\somefile.txt"
Dim lines As New List(Of String)(System.IO.File.ReadAllLines(fileName))
For Each line As String In lines
Dim values() As String = line.Split(",")
If values.Length = 3 Then
If values(0).Trim(Chr(34)) = first AndAlso
values(1).Trim(Chr(34)) = surname AndAlso
values(2).Trim(Chr(34)) = pass Then
validated = True
Exit For
End If
End If
Next
' check the result
If validated Then
MessageBox.Show("Login Successful!")
Else
MessageBox.Show("Login Failed!")
End If
If this is a CSV file, as seems to be the case, then the easiest way to read it will be with the TextFieldParser class. The MSDN already provides an excellent example for how to use it to read a CSV file, so I won't bother reproducing it here.