I am adjusting an existing file transfer windows service that renames the file being sent as a timestamp. For testing purposes, I need to make the files sent show up in the destination directory as being ten days ahead of when they were actually sent. Ex: if it's sent on 11/23/2015, it needs to look like it arrived 12/03/2015.
The line of code that generates the file name looks like this:
Dim strFileNameToTransfer As String = My.Settings.FileDirectory.ToString() & Format(Now(), "yyyy") & Format(Now(), "MM") & Format(Now(), "dd")
File name shows up in directory like this, if sent on 11/23/2015:
"20151123.xml"
But I would need it to show up like this:
"20151203.xml"
It would need to adjust the month as well, since the test will cross over into December and it is now November.
Like I said, this is for testing purposes, so it needs to go back to the way it was when testing is over. I really just need a quick fix here, but I know zero about Visual Basic, and I'm still new to programming in general as well. Help!
All you have to do is add 10 days to the existing date and use that date for your file name. You can also don't need to split the formatting into three different strings.
Dim fileDate = Now().AddDays(10)
Dim strFileNameToTransfer As String = My.Settings.FileDirectory.ToString() & Format(fileDate, "yyyyMMdd")
EDIT:
gmiley is right, it is better to use Path.Combine instead of string concatenation
Dim NameToTransfer As String = System.IO.Path.Combine(My.Settings.FileDirectory.ToString(), String.Format("{0}.{1}", fileDate.ToString("yyyyMMdd"), "xml"))
Related
I am having a heck of a time with something that I think should be so very simple. I think age is getting to me.
All I want to do is in access, run a command that would mimic the following DOS command:
copy c:\1\ABC123-*.txt c:\1\ABC456-*.txt
It seems that filecopy does not support wildcards and for the life of me fso.copyfile just wont work (probably because I am dense). I have also tried to use the copy command using shell and cant get that to work.
To be a little clearer:
The database keeps track of parcels of land. These are "owned" by a land company. On occasion, these parcels are sold from one land company to another. When that happens we have to keep the old records and the new, so the parcel is "copied" to the new land company complete with all its payment history, etc. There are physical documents attached to that record too, and these must appear in BOTH places. I need to copy those PDF files from one parcel number to another (I already have code that duplicates the document entries in the database, I just need to fix the physical files).
So, as an example, parcel 1234 may have a deed, a latenotice, and a survey. Those files would exist as something like 1234-deed.pdf, 1234-latenotice.pdf, and 1234-survey.pdf. I need those files copied to 5678-deed.pdf, 5678-latenotice.pdf, and 5678-survey.pdf after the rest of the database copy code runs.
I need something simple, it only needs to run in that one part of the database so I do not need it to be extensible, or to create a new function, or whatever.
Thanks!
Add reference to "Microsoft Scripting Runtime".
Give this a try:
Dim F As File
Dim FSO As New FileSystemObject
Dim FromPath As String
Dim ToPath As String
FromPath = "C:\1"
ToPath = "C:\1"
Debug.Print FSO.GetFolder(FromPath).Files.Count
For Each F In FSO.GetFolder(FromPath).Files
If Instr(F.Name,"ABC123-") Then
FileCopy FromPath & "\" & F.Name, ToPath & "\" & Replace(F.Name, "123", "456")
End If
Next
I've written an app which brings in a CSV export from our HR system, loops through all the records and applies the values from the HR system to active directory.
It works a treat, and when running on my machine i get no errors whatsoever.
When running it on one of our servers, where it is ultimately going to live and will be executed by a service account, I get date conversion errors...
System.InvalidCastException: Conversion from string "21/08/2020" to type 'Date' is not valid.
Right at the start of my code I'm defining the region...
Dim ukCulture = New Globalization.CultureInfo("en-GB")
System.Threading.Thread.CurrentThread.CurrentCulture = ukCulture
And if I query current culture at runtime, it shows 'en-GB', so that seems right.
If i write out the date strings, they all look right, and the compare operation is working fine.
The error seems to occur in this section of code...
Dim converted_hr_accountexpiry_timestamp= hr_row(0).Item("Termination Date") & ""
Dim hr_termdate_var() As String = converted_hr_accountexpiry_timestamp.split("/")
updatescript = updatescript.Replace("$x", "'" & hr_termdate_var(0) & "'") _
.Replace("$y", "'" & hr_termdate_var(1) & "'") _
.Replace("$z", "'" & hr_termdate_var(2) & "'")
So for context, this code is building up a powershell script which is executed to make the necessary changes in AD.
The section of that powershell code that we're looking at here is this...
$server = "MyPrimaryDNSServer.FQDN"
$exp = get-date -Day $x -Month $y -Year $z -Hour 00 -Minute 00 -Second 00
$expirydate = $exp.ToUniversalTime().AddDays(1)
It seems clear that its trying to use a US date format, because if the date provided would match an acceptable US date, ie 3/5/2020, then it will accept it and the wrong date will be applied. The error is only thrown when the day (dd) portion of the date would not be accepted as MM on an american format date, ie 31/07/2020.
And to re-iterate; this issue doesnt happen on my machine, only on the server that will eventually execute the application. I've been through all the region settings on that device itself and everything is set to united kingdom, with the correct dd/MM/yyyy formats for dates.
I'm at a total loss on this one and pulling out what little hair i have left.
Any suggestions/help appriciated!
EDIT 1:
This is the full exception, minus the users name obvs...
Error with account : Joe Bloggs (1010245)
System.InvalidCastException: Conversion from string "24/07/2020" to type 'Date' is not valid.
at Microsoft.VisualBasic.CompilerServices.Conversions.ToDate(String Value)
at Microsoft.VisualBasic.CompilerServices.Operators.CompareObject2(Object Left, Object Right, Boolean TextCompare)
at Microsoft.VisualBasic.CompilerServices.Operators.CompareObjectEqual(Object Left, Object Right, Boolean TextCompare)
at Atlas.Main.GetAccountsWithUpdates()
EDIT 2:
So it looks like there are two errors occuring, which is why I couldnt find it by commenting each related line out in turn.
This is definately one of the erroring lines...
converted_ad_expiry_timestamp = converted_ad_expiry_timestamp.ToString("dd/MM/yyyy").Split(" ")(0)
The value returned is a datetime not a date, so i use tostring and split it on the space to grab just the date portion.
The second error seems to occur in here...
If Not (converted_hr_expiry_timestamp = converted_ad_expiry_timestamp) Then updateme = True : If (hr_row(0).Item("Termination Date")) = "" Then account_expiration_date = "$null" Else account_expiration_date = converted_hr_expiry_timestamp
It looks like the problem revolves around converted_ad_expiry_timestamp which seems to be a Date (the VB type is an alias for a .NET DateTime). You put it into a specific localized format via converted_ad_expiry_timestamp.ToString("dd/MM/yyyy") and then rely on automated conversion to turn it back into a Date. The way to avoid the problem you see here (where the automated conversion uses the system locale to decide the format) is to use one of the Parse or ParseExact family to control the conversion yourself. With Parse, you can specify the locale to use, or with ParseExact you can specify the format.
Similarly, when you attempt to compare them in If Not (converted_hr_expiry_timestamp = converted_ad_expiry_timestamp) Then ..., the first item in the comparison is a string; if you want to do this comparison, you need to either use ToString on the ad_expiry or parse the hr_expiry into a Date.
I would also recommend using Option Strict if you can to turn these implicit conversions into errors, or if that would introduce to many issues, at least turn on the warning for implicit conversions.
I know this is just working around the problem, and will stop it working locally for you (or rather move the problem to your machine), but if it's only ever going to be run on that server can you not just swap X and Y values?
Dim converted_hr_accountexpiry_timestamp= hr_row(0).Item("Termination Date") & ""
Dim hr_termdate_var() As String = converted_hr_accountexpiry_timestamp.split("/")
updatescript = updatescript.Replace("$x", "'" & hr_termdate_var(1) & "'") _
.Replace("$y", "'" & hr_termdate_var(0) & "'") _
.Replace("$z", "'" & hr_termdate_var(2) & "'")
Alternatively, if you want it to work on both systems then maybe a check before running the offending code is in order, something like this has worked for me in the past:
Try
Dim TempTimeString As String = "31/01/2020 01:00 AM"
Dim ConvertedTime As Date
ConvertedTime = DateTime.Parse(TempTimeString)
'''Don't swap X and Y as it was able to convert
Catch ex As Exception
'''swap X and Y as it was unable to convert
End Try
I have a VB program built in Studio 2017. I need to generate the time in a format which can go on to be used in a filename.
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
spits out 12:00:00 for example and the : isn't usable in a filename.
I could do with either removing the : so it would be 1200000 (not particularly readable but suitable for my purposes) or 12-00-00.
I have checked here and can't see any ToString format that will do the trick.
My code will put a label (say label1) to the current date and time. Another part will use the Label1.Text to grab the string. So any formatting can happen with Label1.
For example, it will be used as follows;
oDoc = oWord.ActiveDocument
oDoc.saveas2("C:\Test\" & "DocumentTitle" & "-" & label1.text & ".docx"
Is there a way to format the Date string to what I want?
Why add the colons in the first place?
DateTime.Now.ToString("yyyy-MM-dd HHmmss")
Simply use the String.Replace
Dim ActualTime as String = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
ActualTime = ActualTime.Replace("/","-").Replace(":","-")
oDoc = oWord.ActiveDocument oDoc.saveas2("C:\Test\" & "DocumentTitle" & "-" & ActualTime & ".docx"
Not the most optimized but clear to understand. Added a one line replace as suggested by Visual Vincent.
Make sure to check his solution as well.
Good morning,
When I want to show the project name & version I use:
System.Windows.Forms.Application.ProductName
System.Windows.Forms.Application.ProductVersion
Is there a similar thing for the last changed date of a project?
At the moment I have a valid workaround (see below), but I wonder if there is a build in solution like with the ones above.
Dim strFile = Application.StartupPath & "\" & Application.ProductName & ".exe"
Return System.IO.File.GetLastWriteTime(strFile.ToString()).ToShortDateString()
I am using visual basic to write a Macro for Autodesk Inventor. I created a macro that calls a file dialog, see code below. Everything works fine except when a user puts a file name in with a period and a number greater than zero following it.
For example, if a user puts testfile.test in the box and hits ok. When I ask for what they put in there using .FileName, I get "testfile.test". Just like I should.
However, if the user puts testfile.1 or testfile.10 or testfile.1mdksj or anything as long as a number greater than zero directly follows the period I get back "testfile". For some reason, everything after the period and the period gets removed.
What is the reason for this? Is this a bug in visual basic or am I doing something wrong?
'Set up the file dialog
Dim oFileDlg As FileDialog
' Create a new FileDialog object.
Call ThisApplication.CreateFileDialog(oFileDlg)
'Define the filter to select part and assembly files or any file.
oFileDlg.Filter = "All Files (*.*)|*.*"
'Define the part and assembly files filter to be the default filter.
oFileDlg.FilterIndex = 1
'Set the title for the dialog.
oFileDlg.DialogTitle = "Save File As"
'Tell the dialog box to throw up and error when cancel is hit by user
oFileDlg.CancelError = True
'Show the file dialog
On Error Resume Next
oFileDlg.ShowSave
'save the user specified file
Dim newFileName As String
newFileName = oFileDlg.FileName
UPDATE:
I ended up doing the following "hack" to make things still work while dealing with a period:
oFileDlg.fileName = sFname & "."
oFileDlg.ShowSave
fullName = Left$(oFileDlg.fileName, Len(oFileDlg.fileName) - 1)
That worked fine for quite a while on Windows 7 and then Windows 10. Unfortunately, the Windows 10 Creative update seems to have changed how the file dialog works. With the above code, fullName would come back blank if there were no periods in the name and would truncate everything from the FIRST period from the left if there was a period in the name.
I'm not really sure what changed in Windows 10, but it pretty much destroyed my hack. Windows 7 still works fine and Windows 10 before the creative update works. I ended up doing the following to make everything work again in the version of Windows I mentioned above.
oFileDlg.fileName = sFname & ".00"
oFileDlg.ShowSave
fullName = Left$(oFileDlg.fileName, Len(oFileDlg.fileName) - 3)
This is a VB property, but it may extend to VBA as well. Have you tried setting the save settings to support multidotted extensions? Try something like this:
SupportMultiDottedExtensions = True
This setting is intended permit the use dotted extensions - meaning the use of periods in the file name. See this MSDN reference for documentation and information: http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.supportmultidottedextensions.aspx#Y129
This SO article may also shed further light: SaveAs Dialog with a period in the filename does not return extension
EDIT
After checking the autodesk documentation - a difficult and unpleasant task, in my opinion - there does indeed appear to be no support for MultidottedExtensions. I did, however, find a function on VBAExpress that I have very closely adapted. The function can be used to filter strings with contain unacceptable characters. Jimmy Pena's blog has an excellent function for just such a purpose: http://www.jpsoftwaretech.com/excel-vba/validate-filenames/. I have only substantively added a period and a replace to the code:
'A function for filtering strings, with a focus on filenames.
Function FilterFileNameString(stringToScrub As String) As String
'Filters a filename string - or any string for that matter.
Dim FilteredString As String
'A highly nested replace function.
FilteredString = Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(stringToScrub, ".","|", ""), ">", ""), "<", ""), Chr(34), ""), "?", ""), "*", ""), ":", ""), "/", ""), "\", "")
'Returns filtered string.
FilterFileNameString = FilteredString
End Function
Jimmy Pena's blog also contains a recursive version as well, although he does not recommend it.
You can filter any strings to be used as filenames with another character - a space in this case. You could use an underscore, however, or any other character you deemed pleasant.
In general, if you are trying to use periods for versioning or a similar purpose, and inventor will not let you, I would strongly advise going to another character or set of characters that can provide such an indication, such an underscore "_", a numbering system, "001", "002", a lettering system, "AAA", "AAB", or whatever makes sense for your focus.
If you are just making the application user-friendly, I would suggest filtering the strings entered before saving them in the desired filetype, and separate the filtering of the strings from the save dialog if the period filtering gives you grief. It may add an extra step, but it may be the best and easiest way to filter out pesky invalid characters without creating unnecessary extra hassles for your users.
~JOL