uninstalling an application and then installing another one using c# - c#

I'm trying to uninstall an application from the system and install a new version of it.
I tried out using Process.start and WaitForExit method in c# code
var process1 = Process.Start(#"C:\Program Files\CPUID\CPU-Z\unins000.exe");
process1.WaitForExit();
var process2 = Process.Start(#"C:\Users\abc\Downloads\Programs\cpu-z_1.71-setup-en.exe");
When the code runs, the setup file for the cpu-z_1.71 launches before the uninstaller exit.
How can i make the installer to wait until I press the OK button of the complete uninstallation dialog box.
Is it possible to do the above task using process or should I use some alternative

You can find a method from below articles.
How to know when a process created by Process.Start() was closed?
Process waitForExit() doesn't work
and this code can be a method.
private void RunNotePad()
{
Process p1 = new Process("notepad.exe");
p1.EnableRaisingEvents = true;
//when process exit, excute ProcessExited function.
p1.Exited += new EventHandler(ProcessExited);
p1.Start();
}
public void ProcessExited(object source, EventArgs e)
{
//start to install a new version
}

Related

How to get VsCode process id after starting it from C#?

i have this C# code (WPF app, but it probably doesnt matter):
void StartEditing(string projectPath) {
InitializeProject(projectPath);
Process process = Process.Start(new ProcessStartInfo(#"path\to\Code.exe", projectPath));
if (!process.HasExited) {
process.Exited += (sender, args) => { CleanupProject(projectPath); }
process.EnableRaisingEvents = true;
}
}
Basically i wanna to do some initialization before vscode starts and then do some cleanup after it exits (start/stop synchronization of changes with remote storage using FileSystemWatcher).
My code works only when there is no Code.exe process already running at time of call Process.Start method.
When there is already another Code.exe process (from different project), then my process exits immediately but vscode window is still opened afterwards (guessing vscode detects previous instance and pass its arguments to it before exiting)
So my question is: How to detect, that vscode opened at projectPath was closed?
PS: on my machine opening folder in vscode spawns 13 Code.exe processes and opening second one spawns additional 3.

How to start/call an Asp.net core app when i open CefSharp(winform) browser and close it on exit?

Tools used: Visual Studio 2019, Asp.net core 5.0, CefSharp.WinForms v79.0
I have created an asp.net core app and a CefSharp browser.
If i click on the app.core and then on the browser it works fine.
I would like to some kind "automate" the whole process.
How to start the Asp.net core app before the CefSharp fully loads/starts.
Can this be done from within the CefSharp browser,
so it opens the app.core in automatic and closes it too when CefSharp is closed?
i can already do this by cmd-line :
tasklist /fi "imagename eq APP.exe" |find ":" > nul
if errorlevel 1 taskkill /F /IM "APP.exe"
start C:\Server\APP.exe
start C:\CEFSHARP\GUI.exe
You can start and stop process "C:\Server\APP.exe" from within GUI.EXE - this is assuming that you have a source code for GUI.EXE
You need to do the following in GUI.EXE source code (here I'm assuming that you are using Windows Forms application):
Add a Load event handler to your main form. From within your event handler you will need to start "C:\Server\APP.exe". You can use System.Diagnostics.Process.Start(#"C:\Server\APP.exe"); within event handler to start a process. Note that this method will return Process object which can be used to close the application.
Add a Closing event handler to your main form. From within your event handler you will need to stop "C:\Server\APP.exe" You can do this via CloseMainWindow method of the Process object.
This worked for me:
Form1.cs
private void Form1_Load(object sender, EventArgs e)
{
Process[] processName = Process.GetProcessesByName("APP");
if (processName.Length == 0)
{
Process myprocess = new Process();
myprocess.StartInfo.FileName = "C:\\Server\\APP.exe";
myprocess.Start();
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
foreach (Process p in Process.GetProcessesByName("APP"))
{
p.Kill();
}
}

Process.StartInfo clarifications c#

I'm trying to run another process from the main one using Process class.
AudioRecordProcess = new Process();
AudioRecordProcess.StartInfo.UseShellExecute = false;
AudioRecordProcess.StartInfo.FileName = #"RecordAudio\RecordAudio";
AudioRecordProcess.StartInfo.CreateNoWindow = true;
The process starts fine but:
Even if I set CreateNoWindow property when I run the code a window is created (the other process is a WPF project with just the main window);
When I try to close the process with closemainwindow it does close nothing. The window just goes under the main process' one.
If I try to kill the process from code it doesn't execute the instructions in my event closing main window, but if I close it from the taskbar it executes that routine. Shouldn't the actions be the same?
Any idea for this strange behavior?
Thanks
Class 'Process' is used to create and/or control and monitor specific process.
Only console application will obey CreateNoWindow = true, while
Windows Forms and WPF applications will ignore it.
Since you have started another process on the system, that process
will continue on its own and will not be terminated once you stop
parent process. However there are some resource lingering (especially
thread and handle related) in the parent process which prevents
parent process termination when its main window is closed.
killing interrupts normal process execution and forces stop as soon
as possible therefore it is normal that closing handlers are not
executed
EDIT:
For test create WPF application and put following code in it:
public MainWindow() {
InitializeComponent();
Loaded += MainWindow_Loaded;
Closed += MainWindow_Closed;
}
private Process process;
private void MainWindow_Closed(object sender, EventArgs e) {
// Log("WpfApp3.log", $"{DateTime.Now} Closed");
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
// Log("WpfApplication3.log", $"{DateTime.Now} Loaded");
process = new Process {
StartInfo = {
UseShellExecute = false,
// FileName = #"..\..\WpfApp2\bin\Debug\WpfApp2.exe",
FileName = #"..\..\CnslApp1\bin\Debug\CnslApp1.exe",
// FileName = #"..\..\WnFrmApp2\bin\Debug\WnFrmApp2.exe",
CreateNoWindow = true
}
};
process.Start();
var result = process.CloseMainWindow();
if (result) {
...
}
}
Then create three new projects; one for each of Console/Windows Forms/WPF. and enter correct path to the executable into 'FileName' paramter of the StartInfo. Then you can play with parameters to see how each will behave.
In my case, process.CloseMainWindow() did had no effect until was moved into another method because process was not started yet. But once moved into a button handler and executed it will terminate all three types (one can be used at the time with this example).
Sole exception was Console application when window was hidden.

Running install process from c# wpf application

In my C# WPF Application in statup process I'm checking whether the installation of new version is required. If so, I want to break current process and start installer. The installer is developed using NSIS package.
The problem is that sometimes only User Account Control dialog from NSIS installer appears and install process breaks.
How to ensure that the installation process is executed every time?
Here is my code on Application Startup.
protected override void OnStartup(StartupEventArgs e)
{
try
{
//Disable shutdown when the dialog closes
Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
if ( IfUpdateRequired())
{
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(sessionCtx.AutoUpdateVersionInfo.SetupPath);
//This should not block current program
startInfo.UseShellExecute = true;
startInfo.Verb = "runas";
System.Diagnostics.Process.Start(startInfo);
this.Shutdown();
}
else
{
base.OnStartup(e);
}
}
catch (Exception ex)
{
}
}
My only guess is that the child process has not fully started before your process quits. ShellExecute is allowed to perform its operation asynchronously.
If this is the cause then you should be able to work around it by sleeping a bit before calling this.Shutdown(). Wait 10 seconds or so perhaps? Or call WaitForInputIdle(9999) on the process. Or maybe you could check the Responding process property?

Closing application and running an external application

I am writing the update system for my application and I need to shutdown the application to overwrite the exe but after it shuts down I need to run the update executable, how can I do this?
Could you just start the updater using Process.Start and have it wait until your main program closes? I think that would be the easiest solution.
Or you could have a separate launcher program that will check for updates and update before launching the main application. But this leads to the same problem if you have to update the launcher.
Along the lines of this:
static void Main(string[] args)
{
var haveToUpdate = ...;
if (haveToUpdate)
{
Process.Start("update.exe");
Environment.Exit(0);
}
}
static void Main(string[] args)
{
var processes = Process.GetProcessesByName("program.exe");
if (processes.Length > 1)
throw new Exception("More than one program.exe running");
else if (processes.Length == 0)
Update();
else
processes[0].Exited += new EventHandler(Program_Exited);
}
static void Program_Exited(object sender, EventArgs e)
{
Update();
}
static void Update()
{
// ...
}
Do it in reverse. Get the entire updated file down using the old application (storing it temporarily) and then start the updater application using process start. All the update has to do is copy the new file over the old file and restart the application.
The updater can catch the access denied exceptions and wait for the application to become available for being copyied over. Once the copy is done - it deletes the temporary new file and starts the application again before shutting down.
Then you can update the updater (using the normal application) if you need to.
I guess you need another small update application. You start it with Process.Start(), let this helper process replace the executable and start up the new one again with Process.Start().
Run the update executable before you shutdown the application.

Categories