vpetkovic
8/7/2019 - 3:12 PM

Initiating an external process

Sometimes it is useful to just initiate some process on button click or sth like that.

public static bool initNewProcess()
        {
            string pathToExe = @"\\path\to\exe";
            elapsedTime = 0;
            eventHandled = false;

            using (myProcess = new Process())
            {
                try
                {
                    // Start a process to print a file and raise an event when done.

                    SecureString theSecureString = new NetworkCredential("", AppSettings.Get<string>("SYSTEM.PASSWORD")).SecurePassword;

                    if (File.Exists(pathToExe))
                    {
                        ProcessStartInfo wic = new ProcessStartInfo(pathToExe);
                        wic.Arguments = "0";
                        wic.UserName = AppSettings.Get<string>("SYSTEM.DOMAIN");
                        wic.UserName = AppSettings.Get<string>("SYSTEM.USERNAME");
                        wic.Password = theSecureString;
                        wic.UseShellExecute = false;
                        var startWIC = Process.Start(wic);
                        startWIC.EnableRaisingEvents = true;
                        startWIC.Exited += new EventHandler(myProcess_Exited);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    //throw new Exception($"An error occurred trying to print \"{pathToExe}\":\n{ex.Message}");
                    return false;
                }

                // Wait for Exited event, but not more than 30 seconds.
                const int SleepAmount = 100;
                while (!eventHandled)
                {
                    elapsedTime += SleepAmount;
                    if (elapsedTime > 30000)
                    {
                        break;
                    }

                    Thread.Sleep(SleepAmount);
                }
            }

            return true;
        }