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
Related
Not sure if this is possible but each day a file will be sent to a folder: Z:\prod\DataProcessing\temp
The file name will look like this: 20230215_UniqueProductsFile.txt
I am wondering if it is possible to
a) search the folder for the version of the file with a date
b) capture the date to use as a parameter for another process
c) rename the file to UniqueProductsFile.txt overwriting the existing one in the folder from the previous days load
Any help would be appreciated.
a) search the folder for the version of the file with a date b) capture the date to use as a parameter for another process
This is possible using the IO.File.Exists method (documentation) to check if the file exists. For example:
Private Function UniqueProductsFileExistsByDate(directory As String, value As DateTime, ByRef output As String) As Boolean
Dim filename = $"{value:yyyyMMdd}_UniqueProductsFile.txt"
Dim path = IO.Path.Combine(directory, filename)
Dim fileExists = IO.File.Exists(path)
If (fileExists) Then
output = path
End If
Return fileExists
End Function
c) rename the file to UniqueProductsFile.txt
This is possible using IO.File.Move (documentation) where the first argument is the ByRef value set in the UniqueProductsFileExistsByDate method and the second argument is the new name:
Dim directory = IO.Path.Combine("Z:", "prod", "DataProcessing", "temp")
Dim value = DateTime.Today
Dim path As String
If (UniqueProductsFileExistsByDate(directory, value, path)) Then
Dim newPath = IO.Path.Combine(directory, "UniqueProductsFile.txt")
IO.File.Move(path, newPath)
End If
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
I had a problem manipulating the textbox. This is the date format 2019-10-10 05-21-27 and I was about to convert it using datetime. But it seems it cannot be Format like this 2019-10-10 05:21:27 I tried several codes for this one but it did not work.
Here is my code:
Dim d As Date = Date.ParseExact(tbox_dateofS.Text, "d/M", CultureInfo.InvariantCulture)
tbox_dateofS.Text = d.ToString("dd/MM/yy hh:mm:ss")
i tried this one also:
tbox_dateofS.Text = Cdate(node.SelectSingleNode("starttime").InnerText).Tostring("yyyy-mm/dd hh:mm:ss"
And I got this error : System.FormatException: 'String was not recognized as a valid DateTime.'
Of course it can be formatted like that. You simply need to specify the correct format to convert FROM in order to get a Date that you can then format however you want.
Imports System.Globalization
Module Module1
Sub Main()
Dim text = "2019-10-10 05-21-27"
Dim dt As Date
If Date.TryParseExact(text, "yyyy-MM-dd HH-mm-ss", Nothing, DateTimeStyles.None, dt) Then
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"))
Else
Console.WriteLine("Invalid input")
End If
Console.ReadLine()
End Sub
End Module
It works exactly as you should expect.
That said, why use a TextBox in the first place? In most cases, you can use a DateTimePicker and it will handle all the formatting and validation for you.
05-21-27 is a bad format (WITH FORMAT STYLE "d/M") to convert in a time object.
So if you don’t want to change your INPUT format use the method below as a workaround otherwise in order to have a correct date Object you need to change your time input string in 05:21:27 and after to format this date in your style again as you want.
Private Function getFormatedDate(sDate As String, Optional formatString As String = "yyyy-MM-dd HH:mm:ss")
Dim correctDateString As String = ""
For i As Integer = 0 To sDate.Length - 1
If IsNumeric(CChar(sDate(i))) OrElse sDate(i) = " " Then
correctDateString &= sDate(i)
Else
If i < 10 Then
correctDateString &= "/"
Else
correctDateString &= ":"
End If
End If
Next
Return Strings.Format(CDate(correctDateString), formatString)
End Function
Usage:
Dim mCorrectDateString As String = getFormatedDate("2019-10-10 05-21-27")
I'm having an issue where I need to strip a filename from a path but can't quite figure out the code.
An example filename would be C:\Checked out parts\001-1099-01.slddrw. I need to extract the "001-1099-01." portion. The file location to the left could be anything and the only constants in the file name are the "001-" portion (which I should point out, could repeat if the filename was 001-1001-03) and the ".slddrw". Other than that the filename could be named "001-10999-03-02-01".
I have stripped out the slddrw portion easily, I tried using Right and InStr functions to strip the rest off but I think that InStr only works with letters (couldn't find any number examples anyways)
I believe this is what you are looking for:
Public Sub test()
Dim strFileName As String
'Your sample file name
strFileName = "C:\Checked out parts\001-1099-01.slddrw"
'Search for the first occurance of \ in the reversed (!) file name
' if you substract this result from the length of the string
' you know where to start (+ 2 to avoid the \ itself)
strFileName = Mid(strFileName, Len(strFileName) - InStr(1, StrReverse(strFileName), "\") + 2)
'Remove the .slddrw portion from the end
strFileName = Replace(strFileName, ".slddrw", "")
'Done
Debug.Print strFileName
End Sub
Note the comments in the code for more information.
You can use a sub in which you define the path and extension of your file and it will give you the filename.
Sub getFileName()
Dim myString() As String
Dim path As String, extension As String
Dim fileName As String
path = "C:\Checked out parts\"
extension = ".slddrw"
'Say your string is in cell A1
myString = Split(Range("A1"), path)
fileName = Split(myString(1), extension)(0)
MsgBox fileName 'fileName can be used elsewhere after
End Sub
You could also do it as a function:
Function getFileName(cel As Range, path As String, extension As String)
Dim myString() As String
myString = Split(cel, path)
getFileName = Split(myString(1), extension)(0)
End Function
If you have the path and extensions stored in cells, you can use this function:
Function getFileName2(cel As Range, path As Range, extension As Range)
Dim myString() As String
myString = Split(cel, path)
getFileName2 = Split(myString(1), extension)(0)
End Function
Those are the options I can think of, hope it helps.
EDIT:
If you don't know the path nor the extension, you can use this instead:
myString = Split(Range("A1"), "\")
fileName = Split(myString(UBound(myString)), ".")(0)
Afternoon,
How can I tailor the below function in VB.net to pickup the first 8 characters of the second part of the filename in the array?
Private Function GetFormattedDateFromFileName(ByVal fileName As String) As String
Dim parts() As String = fileName.Split("-")
If parts.Length = 3 Then
Dim dt As DateTime
If DateTime.TryParseExact(parts(1), "yyyyMMdd", Nothing, Globalization.DateTimeStyles.None, dt) Then
Return dt.ToString("MM/dd/yyyy")
End If
End If
Return ""
End Function
I was using this function before because the filename would be split in 3 parts so this worked perfect for me. File name looked like below before:
542656-20130402-FTO Disclosure.pdf
548872-20120501-Funds a.pdf
848581-20110215-Alpha.pdf
Problem now is that the filename structure has been changed and will now be in 2 parts like so:
542656-20130402.pdf
548872-20120501.pdf
848581-20110215 Alpha.pdf
652162-20120711 a.pdf
So how would I go about to tailor the above function to still split the filename with the “-“ but instead of trying to parse the date exactly, for it to just look at the first 8 characters of the second part (being the date) and continue on as it has been with the rest of the code?
Kindly advise.
A
If you change your split call and length check to:
Dim parts() As String = fileName.Split("-"c, "."c, " "c)
If parts.Length > 2 Then
Then the existing code should work correctly on both versions.
Edit in response to comment:
In order to make this work on files like "12764-20120124b.pdf", you'll need to just extract the substring directly:
Private Function GetFormattedDateFromFileName(ByVal fileName As String) As String
Dim parts() As String = fileName.Split("-")
If parts.Length > 1 AndAlso parts(1).Length >= 8 Then
Dim dt As DateTime
Dim dtStr = parts(1).Substring(0, 8)
If DateTime.TryParseExact(dtStr, "yyyyMMdd", Nothing, Globalization.DateTimeStyles.None, dt) Then
Return dt.ToString("MM/dd/yyyy")
End If
End If
Return ""
End Function