So how can I delete a old file once it's updated? I'm making a program were once it's updated to delete the old version. I don't have a installer so I wouldn't know the location of the file. How can I delete it after it's updated and I don't know were the user put the file that I need to delete? I've searched and everything that shows up you need to have the path.
You could use ClickOnce as suggested, but if you really don't want to use any "external" tools.. this might do the job:
Sorry for my coding, i use this snipet in some of my projects aswell and it works quite good.
This is used in the application that is being updated...
fileupdatepath = "The path to your file which is the updated one you downloaded."
Dim pi As New ProcessStartInfo("cmd.exe", String.Format("/c ping 1.1.1.1 -n 1 -w 15000 >NUL & move /y {0} {1} & start {1}", fileupdatedpath, Application.ExecutablePath)) With {.CreateNoWindow = True, .UseShellExecute = False}
Process.Start(pi)
Application.Exit()
This waits 15s to ensure the current application is closed properly before starting the new one, this is used if the same name and application path needs to be kept, as the move command is being used to replace any files with the same name., if not you can just start the new one, close the current, and delete the current application file...
Note: 'This works if the application path has no special characters like '#' or ' '
In the above answer, you can put quotes around the fileupdatepath and application.executablepath and the code will work even if if there is a space in the file locations. The final code will look like this:
fileupdatepath = "The path to your file which is the updated one you downloaded."
Dim pi As New ProcessStartInfo("cmd.exe", String.Format("/c ping 1.1.1.1 -n 1 -w 15000 >NUL & move /y {0} {1} & start {1}", """" & fileupdatedpath& """", """" & Application.ExecutablePath & """")) With {.CreateNoWindow = True, .UseShellExecute = False}
Process.Start(pi)
Application.Exit()
Related
I am trying to write some VBA in Excel that will concatenate .csv files by executing the copy and more commands in the Windows Shell.
This code successfully creates an empty file concat_target.txt (into which the others will be concatenated):
Shell ("cmd.exe copy /b NUL " & """\\path\to\network\folder\concat_target.txt""")
However, this code does not have the intended effect of saving file_1.txt as file_1.concat_temp (skipping the header):
Shell ("cmd.exe more +1 " & """\\path\to\network\folder\file_1.txt""" & " > " & """\\path\to\network\folder\file_1.concat_temp""")
In fact, every variation of the call to more that I have tried just pops up a console (that stays open) whereas the call to copy does not. The UNC network path has cursed spaces in it.
UPDATE:
It turns out that adding the /c flag to the more command does the trick (although it seems to have no effect on the call to copy). So this code is having the desired effect:
Shell ("cmd.exe /c more +1 " & """\\path\to\network\folder\file_1.txt""" & " > " & """\\path\to\network\folder\file_1.concat_temp""")
I will post the full solution for posterity once it is finished.
I don´t know why you are using 'more', but I would use other methods:
Shell ("cmd.exe /c type ""\\path\to\network\folder\file_1.txt"" >> ""\\path\to\network\folder\file_1.concat_temp""")
Notes:
redirecting with '>' will overwrite the file, losing previous contents
redirecting with '>>' will append the file (concatenate)
no need to separate every element in your string with " & " if they are all text (but I guess you already knew this)
no need to create an empty file first.
UPDATE:
OP was using 'more' to exclude the .csv table headers, as I hadn´t understood before.
So the 'type' command won´t work in this case.
Hi I have a perfectly working bat named: start.bat
containing:
start C:\Users\*user*\Documents\*path*\hidebat.vbs
and once it is manually opened it works perfectly, meaning it opens hidebat.vbs, which opens a .bat minimized which uploads files to my cloud. Hence it's verified.
I've added
pause
to the start.bat to see what it does and when I tell excel to open the start.bat it will open cmd and display the exact command as required, but it will not execute the hidebat.vbs.
I expect that there is somehow some path constraint or environment constraint when it is run from excel that prevents it to actually reach out of that limited environment.
Within excel I have tried calling the .bat in 3 different ways with:
Dim path As String
path = Application.ActiveWorkbook.path
path = path & "\"
Dim MY_FILENAME3 As String
MY_FILENAME3 = path & "start.bat"
1.
retVal = Shell(MY_FILENAME3, vbNormalFocus)
' NOTE THE BATCH FILE WILL RUN, BUT THE CODE WILL CONTINUE TO RUN.
If retVal = 0 Then
MsgBox "An Error Occured"
Close #FileNumber
End
End If
2.
PathCrnt = ActiveWorkbook.path
Call Shell(PathCrnt & "start.bat")
3.
Dim batPath As String: batPath = path
Call Shell(Environ$("COMSPEC") & " /c " & batPath & "start.bat", vbNormalFocus)
Does anybody have any clue on why it will not execute the .bat file, or what I could do to ensure it will run correctly?
Note. I think it is because it opens the default path, so I'm gonna tell it to "cd" to the actual path where the excel is saved and where the .bat files are.
Yes that was it, the path was set to some random/standard/working/current path by command, so I had to add:
Print #FileNumber, "cd " & path
to the excel macro
so that start.bat looked like:
cd *path*
start *path*\hidebat.vbs
Hope this helps future me's.
I need to install my win service. With installUtil it is just few lines of code.
#ECHO OFF
REM The following directory is for .NET 2.0
set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727
set PATH=%PATH%;%DOTNETFX2%
echo Installing MyService...
echo ---------------------------------------------------
InstallUtil /i MyService.exe
echo ---------------------------------------------------
echo Done.
pause
But my thoughts are without creating .bat file and then runing it.
Is there any way i can ".execute" those lines of code above without creating .bat file runing it and then deleting it ?.
I will need to dynamically create this code every time because i need to enter the username/password depending what user entered on .net form.
You could start cmd and doing it in one line via it's arguments:
Process.Start("cmd.exe", "/k set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727 & set PATH=%PATH%;%DOTNETFX2% & InstallUtil /i MyService.exe")
And if you want it to show the text you wrote and to "pause" (stay open):
Process.Start("cmd.exe", "/k set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727 & set PATH=%PATH%;%DOTNETFX2% & echo Installing MyService... & echo --------------------------------------------------- & InstallUtil /i MyService.exe & echo --------------------------------------------------- & echo Done. & pause")
Commands are separated by " & ".
I know it's been a month since you first asked this, but I recently came up with a pretty good solution to this - only using this simple VB.NET code:
Public Sub InstallService(ByVal ServicePath As String)
Dim InstallUtilPath As String = IO.Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), "installutil.exe")
Dim InstallUtilProcess As Process = Process.Start(InstallUtilPath, """" & ServicePath & """")
InstallUtilProcess.WaitForExit()
'Service is now installed.
InstallUtilProcess = Process.Start(InstallUtilPath, "/i """ & ServicePath & """")
InstallUtilProcess.WaitForExit()
'The second action is now done. Show a MessageBox or something if you'd like.
End Sub
The ServicePath parameter is the path to the service that you want to install.
The InstallUtilPath variable will be set to the path of the installutil.exe application. It will get the path for the current framework you're running.
As I'm running .NET Framework 4 the path is C:\Windows\Microsoft.NET\Framework\v4.0.30319\installutil.exe
Hope this helps!
I'm working on a program created with Visual Studio 2013. The program does a few things and I'm nearly complete, but one last issue appears.
Within the program I have three buttons. One "Force restart", "manual start" and one "force stop". The "force stop" stops a bunch of programs, and the "force restart" stops them and then starts them again. The "manual start" starts all the programs. I will use "manual start" as example further down.
What happens behind these buttons is that it launches a bunch of bat-files that does the job. The batfiles contains tasskill /f /im program.exe and start "c:\program.exe". Then a second with timeout and exits.
The issue:
So far so good. The issue is that when the batch starts a program, VB program doesnt move on the the next bat file. It leaves a cmd.exe running. Even tho I have exit in the batch. Now If I'd go in and manually close the program or cmd.exe, then it would start on the next bat file.
It basically goes like this now: VB button -> batch starts -> batch runs program -> batch doesn't close AKA VB doesn't move to the next batch.
It should be like this: VB button -> batch starts -> batch runs program -> batch exits -> next batch starts -> batch runs program -> batch exits ->...
Here is what I got so far in that section of VB script:
Private Sub btnManualStart_Click(sender As Object, e As EventArgs) Handles btnManualStart.Click
If MessageBox.Show("Do you want to manually start all programs and services?", "OBS", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
Timer2.Start()
Dim FileNum As Integer = FreeFile()
FileClose(FileNum)
TextBox1.Text &= Environment.NewLine & TimeOfDay & (" Manual start made")
Dim shell
shell = CreateObject("wscript.shell")
shell.run("C:\RestartApps\Scripts\Start_program1.bat", 0, True)
shell.run("C:\RestartApps\Scripts\Start_program2.bat", 0, True)
shell.run("C:\RestartApps\Scripts\Start_program3.bat", 0, True)
shell.run("C:\RestartApps\Scripts\Start_program4.bat", 0, True)
shell = Nothing
end if
Hopefully this was understandable.
I do not know exactly what your batches are doing, but it seems to me that you can simply use the Shell shortcut:
Dim commands As String() = {
"C:\RestartApps\Scripts\Start_program1.bat",
"C:\RestartApps\Scripts\Start_program2.bat",
"C:\RestartApps\Scripts\Start_program3.bat",
"C:\RestartApps\Scripts\Start_program4.bat"
}
For Each cmd As String In commands
Shell(cmd, AppWinStyle.Hide, False)
Next
Make sure that you set the third argument to FALSE on the overload (String,AppWinStyle,Boolean). This boolean ensures that the execution is set to "fire and forget". (which is the same as the one you're already passing, as TRUE (will wait for exit code)).
EDIT: Changed the AppWinStyle to Hide, which will run your batches silently
You need to improve start used in your batch script(s) as follows:
start "" /B "c:\program.exe"
Start command: start a program, command or batch script (opens in a new window). Note:
"" always include a TITLE this can be a simple string or just a pair of empty quotes "";
/B start application without creating a new window.
Another approach: use call instead of start "" as follows:
call "c:\program.exe"
In Access VBA, I have a procedure I've put together to do this:
Allow the user to select zip file(s)
Extract any files from the zip files to the same directory (In this
specific use-case instance, it is ALWAYS extracting Excel files from
Zip files, never any change, and always using the same password)
Then I want the code to Delete the Zip file after extracting the
.xls file.
Everything works beautifully except the delete file portion. The issue is that when I tell it to delete "FileName.Zip", it is deleting "FileName.Zip" AND "FileName.xls"
Is there any way to make sure that he kill command ONLY deletes what I want it to delete? I've used it before on various occasions, and never had this happen before.
Here is the code I am using:
Dim fd As FileDialog
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim i As Variant
Set db = CurrentDb
Set rs = db.OpenRecordset("tblProjectPath")
Set fd = FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = True
fd.Title = "Select TOC Return File(s) to process"
fd.InitialFileName = rs.Fields("ProjectPath") & "\FilingReports\*.zip"
fd.Show
For Each i In fd.SelectedItems
'Debug.Print i
Debug.Print '------------------------'
Debug.Print i
Unzip (i) 'The bit calling the command line unzip utility to unzip the file - just telling it to extract all files to the current folder.
Debug.Print i
'Kill i
'had to take out the kill bit, b/c it was deleting both the .zip and .xls files which is not desired nor expected
If InStr(i, ".zip") Then
Kill i 'Tried to specify only .zip files even though think I shouldn't need to, but it's still deleting .xls files
End If
Next i
Edit: Add Unzip code to post:
Unzip code:
Sub Unzip(Path As String)
Dim strUnzip As String
Dim QU As String 'quotation mark
QU = Chr(34)
strUnzip = QU & "c:\program files (x86)\winzip\wzunzip" & QU & " -s" & _
"ZipPassword " & _
Path & " " '& _
Call Shell(strUnzip)
End Sub
At this point, I don't really think a "real" answer will come about. However, I'll post what I've decided to do with the particular process I'm writing this code for anyway.
I'm going to use a folder structure to divide up the files:
1. Place zip file(s)
2. Unzip files to a 2nd folder
3. After processing Excel files in 2nd folder, move to a 3rd "complete" folder.
This will get around the deleting wrong files bit.
Also, it appears that the cause for the issue is related to something to do with the call to the WinZip Command Line Unzip utility (wzunzip) in the Unzip code above, or else something with the tool itself. I thought that maybe it was b/c the tool was asking me if I wanted to overwrite existing files, but that wasn't the case, b/c I had the same issue when there were no files to overwrite.
Anyway, I'm attempting to close this one up at this point. Thanks to Wayne G. Dunn for his assistance on this.