System.Diagnostics.Process.WaitForExit()

Here are the examples of the csharp api System.Diagnostics.Process.WaitForExit() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2117 Examples 7

19 Source : Updater.xaml.cs
with MIT License
from Alkl58

public void ExtractFile(string source, string destination)
        {
            // Extracts the downloaded archives with 7zip
            string zPath = Path.Combine(CurrentDir, "Apps", "7zip", "7za.exe");
            // change the path and give yours
            try
            {
                ProcessStartInfo pro = new ProcessStartInfo
                {
                    WindowStyle = ProcessWindowStyle.Hidden,
                    FileName = zPath,
                    Arguments = "x \"" + source + "\" -aoa -o" + '\u0022' + destination + '\u0022'
                };
                Process x = Process.Start(pro);
                x.WaitForExit();
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

19 Source : AudioEncode.cs
with MIT License
from Alkl58

public static void EncodeAudio(string videoInput, bool logging, string audioBitrate, string audioCodec, string currentPath, string ffmpegPath, bool trackone, bool tracktwo, bool trackthree, bool trackfour)
        {
            if (logging == true)
            {
                SmallScripts.WriteToFileThreadSafe(DateTime.Now.ToString("h:mm:ss tt") + " Audio Encoding started", "log.log");
            }

            string allAudioSettings = "";
            //Sets Settings for Audio Encoding
            if (audioCodec == "Copy Audio")
            {
                if (logging == true)
                {
                    SmallScripts.WriteToFileThreadSafe(DateTime.Now.ToString("h:mm:ss tt") + " Audio Encoding Setting Encode Mode to Audio Copy", "log.log");
                }
                allAudioSettings = " -c:a copy";
            }
            else if (audioCodec == "Opus")
            {
                if (logging == true)
                {
                    SmallScripts.WriteToFileThreadSafe(DateTime.Now.ToString("h:mm:ss tt") + " Audio Encoding Setting Encode Mode to libopus", "log.log");
                }
                allAudioSettings = " -c:a libopus -b:a " + audioBitrate + "k ";
            }
            else if (audioCodec == "Opus 5.1")
            {
                if (logging == true)
                {
                    SmallScripts.WriteToFileThreadSafe(DateTime.Now.ToString("h:mm:ss tt") + " Audio Encoding Setting Encode Mode to libopus 5.1", "log.log");
                }
                allAudioSettings = " -c:a libopus -b:a " + audioBitrate + "k -af channelmap=channel_layout=5.1";
            }
            else if (audioCodec == "AAC CBR")
            {
                if (logging == true)
                {
                    SmallScripts.WriteToFileThreadSafe(DateTime.Now.ToString("h:mm:ss tt") + " Audio Encoding Setting Encode Mode to AAC CBR", "log.log");
                }
                allAudioSettings = " -c:a aac -b:a " + audioBitrate + "k ";
            }
            else if (audioCodec == "AC3")
            {
                if (logging == true)
                {
                    SmallScripts.WriteToFileThreadSafe(DateTime.Now.ToString("h:mm:ss tt") + " Audio Encoding Setting Encode Mode to AC3 CBR", "log.log");
                }
                allAudioSettings = " -c:a ac3 -b:a " + audioBitrate + "k ";
            }
            else if (audioCodec == "FLAC")
            {
                if (logging == true)
                {
                    SmallScripts.WriteToFileThreadSafe(DateTime.Now.ToString("h:mm:ss tt") + " Audio Encoding Setting Encode Mode to FLAC", "log.log");
                }
                allAudioSettings = " -c:a flac ";
            }
            else if (audioCodec == "MP3 CBR")
            {
                if (logging == true)
                {
                    SmallScripts.WriteToFileThreadSafe(DateTime.Now.ToString("h:mm:ss tt") + " Audio Encoding Setting Encode Mode to MP3 CBR", "log.log");
                }
                allAudioSettings = " -c:a libmp3lame -b:a " + audioBitrate + "k ";
            }
            else if (audioCodec == "MP3 VBR")
            {
                if (logging == true)
                {
                    SmallScripts.WriteToFileThreadSafe(DateTime.Now.ToString("h:mm:ss tt") + " Audio Encoding Setting Encode Mode to MP3 CBR", "log.log");
                }
                if (Int16.Parse(audioBitrate) >= 10)
                {
                    MessageBox.Show("Audio VBR Range is from 0-9");
                }
                else if (Int16.Parse(audioBitrate) <= 10)
                {
                    allAudioSettings = " -c:a libmp3lame -q:a " + audioBitrate + " ";
                }
            }
            else if (audioCodec == "Opus Downmix")
            {
                if (logging == true)
                {
                    SmallScripts.WriteToFileThreadSafe(DateTime.Now.ToString("h:mm:ss tt") + " Audio Encoding Setting Encode Mode to Opus Downmix", "log.log");
                }
                allAudioSettings = " -c:a libopus -b:a " + audioBitrate + "k -ac 2";
            }

            //Creates Audio Folder
            if (!Directory.Exists(Path.Combine(currentPath, "AudioExtracted")))
                Directory.CreateDirectory(Path.Combine(currentPath, "AudioExtracted"));
            if (!Directory.Exists(Path.Combine(currentPath, "AudioEncoded")))
                Directory.CreateDirectory(Path.Combine(currentPath, "AudioEncoded"));

            Process process = new Process();
            //Starts extracting maximal 4 Audio Streams
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;
            startInfo.WorkingDirectory = ffmpegPath;
            startInfo.FileName = "cmd.exe";

            if (trackone == true && tracktwo == true && trackthree == true && trackfour == true)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:0 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:1 " + '\u0022' + currentPath + "\\AudioExtracted\\audio1.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:2 " + '\u0022' + currentPath + "\\AudioExtracted\\audio2.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:3 " + '\u0022' + currentPath + "\\AudioExtracted\\audio3.mkv" + '\u0022';
            }
            //Only One out of Four Tracks
            //1st Track
            if (trackone == true && tracktwo == false && trackthree == false && trackfour == false)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:0 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022';
            }
            //2nd Track
            if (trackone == false && tracktwo == true && trackthree == false && trackfour == false)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:1 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022';
            }
            //3rd Track
            if (trackone == false && tracktwo == false && trackthree == true && trackfour == false)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:2 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022';
            }
            //4th Track
            if (trackone == false && tracktwo == false && trackthree == false && trackfour == true)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:3 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022';
            }

            //Two out of Four Tracks
            //1st & 2nd     //                   //
            if (trackone == true && tracktwo == true && trackthree == false && trackfour == false)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:0 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:1 " + '\u0022' + currentPath + "\\AudioExtracted\\audio1.mkv" + '\u0022';
            }
            //1st & 3rd     //                                          //
            if (trackone == true && tracktwo == false && trackthree == true && trackfour == false)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:0 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:2 " + '\u0022' + currentPath + "\\AudioExtracted\\audio1.mkv" + '\u0022';
            }
            //1st & 4th     //                                                               //
            if (trackone == true && tracktwo == false && trackthree == false && trackfour == true)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:0 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:3 " + '\u0022' + currentPath + "\\AudioExtracted\\audio1.mkv" + '\u0022';
            }
            //2nd & 3rd                          //                     //
            if (trackone == false && tracktwo == true && trackthree == true && trackfour == false)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:1 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:2 " + '\u0022' + currentPath + "\\AudioExtracted\\audio1.mkv" + '\u0022';
            }
            //2nd & 4th                          //                                          //
            if (trackone == false && tracktwo == true && trackthree == false && trackfour == true)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:1 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:3 " + '\u0022' + currentPath + "\\AudioExtracted\\audio1.mkv" + '\u0022';
            }
            //3rd & 4th                                                 //                   //
            if (trackone == false && tracktwo == false && trackthree == true && trackfour == true)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:2 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:3 " + '\u0022' + currentPath + "\\AudioExtracted\\audio1.mkv" + '\u0022';
            }

            //Three out of Four Tracks
            //1st & 2nd & 3rd //                   //                    //
            if (trackone == true && tracktwo == true && trackthree == true && trackfour == false)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:0 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:1 " + '\u0022' + currentPath + "\\AudioExtracted\\audio1.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:2 " + '\u0022' + currentPath + "\\AudioExtracted\\audio2.mkv" + '\u0022';
            }
            //1st & 2nd & 4th //                   //                                       //
            if (trackone == true && tracktwo == true && trackthree == false && trackfour == true)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:0 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:1 " + '\u0022' + currentPath + "\\AudioExtracted\\audio1.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:3 " + '\u0022' + currentPath + "\\AudioExtracted\\audio2.mkv" + '\u0022';
            }
            //1st & 3rd & 4th //                                       //                   //
            if (trackone == true && tracktwo == false && trackthree == true && trackfour == true)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:0 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:2 " + '\u0022' + currentPath + "\\AudioExtracted\\audio1.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:3 " + '\u0022' + currentPath + "\\AudioExtracted\\audio2.mkv" + '\u0022';
            }
            //2nd & 3rd & 4th                      //                  //                   //
            if (trackone == false && tracktwo == true && trackthree == true && trackfour == true)
            {
                startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:1 " + '\u0022' + currentPath + "\\AudioExtracted\\audio0.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:2 " + '\u0022' + currentPath + "\\AudioExtracted\\audio1.mkv" + '\u0022' + " & ffmpeg.exe -i " + '\u0022' + videoInput + '\u0022' + " -vn -map_metadata -1 -c copy -map 0:a:3 " + '\u0022' + currentPath + "\\AudioExtracted\\audio2.mkv" + '\u0022';
            }

            Console.WriteLine(startInfo.Arguments);
            process.StartInfo = startInfo;
            process.Start();
            process.WaitForExit();
            Console.WriteLine(currentPath + "\\AudioExtracted");
            DirectoryInfo AudioExtracted = new DirectoryInfo(currentPath + "\\AudioExtracted");
            //Loops through all mkv files in AudioExtracted
            foreach (var file in AudioExtracted.GetFiles("*.mkv"))
            {
                //Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
                //Get the Filesize, because the command above also creates mkv files even if there is not audiostream (filesize = 0)
                long length = new FileInfo(currentPath +"\\AudioExtracted\\" + file).Length;
                //Console.WriteLine(length);
                //If Filesize = 0 -> delete file
                if (length == 0)
                {
                    File.Delete(currentPath + "\\AudioExtracted\\" + file);
                }
                else if (length > 1)
                {
                    //Encodes the Audio to the given format
                    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    startInfo.FileName = "cmd.exe";
                    startInfo.WorkingDirectory = ffmpegPath;
                    startInfo.Arguments = "/C ffmpeg.exe -i " + '\u0022' + currentPath + "\\AudioExtracted\\" + file + '\u0022' + " " + allAudioSettings + "-vn " + '\u0022' + currentPath + "\\AudioEncoded\\" + file + '\u0022';
                    Console.WriteLine(startInfo.Arguments);
                    process.StartInfo = startInfo;
                    process.Start();
                    process.WaitForExit();
                }
            }
            //Counts the number of AudioFiles
            int audioCount = Directory.GetFiles(currentPath + "\\AudioEncoded", "*mkv", SearchOption.TopDirectoryOnly).Length;
            //Sets the number of AudioTracks of the concat process
            MainWindow.SetNumberOfAudioTracks(audioCount);
        }

19 Source : SmallScripts.cs
with MIT License
from Alkl58

public static void GetStreamLength(string fileinput)
        {
            string input;

            input = '\u0022' + fileinput + '\u0022';

            Process process = new Process();
            process.StartInfo = new ProcessStartInfo()
            {
                UseShellExecute = false,
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                FileName = "cmd.exe",
                WorkingDirectory = MainWindow.ffprobePath + "\\",
                Arguments = "/C ffprobe.exe -i " + input + " -show_entries format=duration -v quiet -of csv=" + '\u0022' + "p=0" + '\u0022',
                RedirectStandardError = true,
                RedirectStandardOutput = true
            };
            process.Start();
            string streamlength = process.StandardOutput.ReadLine();
            //TextBoxFramerate.Text = fpsOutput;
            //Console.WriteLine(streamlength);
            string value = new DataTable().Compute(streamlength, null).ToString();
            streamLength = Convert.ToInt64(Math.Round(Convert.ToDouble(value))).ToString();
            //streamLength = streamlength;
            //Console.WriteLine(streamLength);
            MainWindow.SetStreamLength(streamLength);
            process.WaitForExit();
        }

19 Source : PdfImageConverter.cs
with MIT License
from allantargino

private async Task<string[]> ConvertAsync(string input, string ratio = "102.4")
        {
            var filename = new FileInfo(input).Name.Replace(".pdf", "");
            var outdir = new FileInfo(input).FullName.Replace(".pdf", "");
            Directory.CreateDirectory(outdir);

            string output = "", err = "";

            try
            {
                int exitCode = await Task.Run(() =>
                {
                    String args = $@"-dNOPAUSE -sDEVICE=jpeg -r{ratio} -o""{outdir}/{filename}_%d.jpg"" ""{input}""";
                    Console.WriteLine($"GS command line: {args}");

                    Process proc = new Process();
                    proc.StartInfo.FileName = _gsPath;
                    proc.StartInfo.Arguments = args;
                    proc.StartInfo.UseShellExecute = false;
                    proc.Start();
                    proc.WaitForExit();
                    return proc.ExitCode;
                });

                Thread.Sleep(500);
                File.Delete(input);

                if (exitCode == 0)
                {
                    Console.WriteLine($"outdir: {outdir}");
                    return Directory.GetFiles(outdir, "*.jpg");
                }
                else
                {
                    Console.WriteLine($"ExitCode: {exitCode} gs: {_gsPath} out: {output} err: {err} ");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error generating image from pdf: {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
            return null;
        }

19 Source : IntegrationTests.cs
with Apache License 2.0
from allure-framework

[OneTimeSetUp]
    public void Init()
    {
      var featuresProjectPath = Path.GetFullPath(
        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"./../../../../Allure.Features"));
      Process.Start(new ProcessStartInfo
      {
        WorkingDirectory = featuresProjectPath,
        FileName = "dotnet",
        Arguments = $"test"
      }).WaitForExit();
      var allureResultsDirectory = new DirectoryInfo(featuresProjectPath).GetDirectories("allure-results", SearchOption.AllDirectories)
        .First();
      var featuresDirectory = Path.Combine(featuresProjectPath, "TestData");
    

      // parse allure suites
      ParseAllureSuites(allureResultsDirectory.FullName);
      ParseFeatures(featuresDirectory);
    }

19 Source : DumpCreator.cs
with GNU Lesser General Public License v3.0
from Alois-xx

private bool CanLoadDump(string dumpFileName)
        {
            ProcessStartInfo info = new ProcessStartInfo(replacedembly.GetEntryreplacedembly().Location, $"-f {dumpFileName} -vmmap")
            {
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true,
            };

            var p = Process.Start(info);
            Console.WriteLine("Verifying Dump if it is readable ...");
            Console.WriteLine(p.StandardOutput.ReadToEnd());
            DebugPrinter.Write($"Start child process {info.FileName} with args: {info.Arguments}");
            p.WaitForExit();
            return p.ExitCode > 0;
        }

19 Source : VMMap.cs
with GNU Lesser General Public License v3.0
from Alois-xx

public static void SaveVMmapDataToFile(int pid, string outFile)
        {
            var info = new ProcessStartInfo(VmMap, $"-accepteula -p {pid} {outFile}")
            {
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
            };

            try
            {
                var p = Process.Start(info);
                p.WaitForExit();

                // Looks like a bug in VMMap where the x64 child process is still writing the output data but the
                // x86 parent process has already exited.
                for (int i = 0; i < 10 && !File.Exists(outFile); i++)
                {
                    DebugPrinter.Write($"VMMap has exited but output file {outFile} does not yet exist");
                    Thread.Sleep(2000);
                }
            }
            catch (Exception ex)
            {
                NoVMMap = true; // do not try again if not present.
                DebugPrinter.Write($"Could not start VMMap: {info.FileName} {info.Arguments}. Got: {ex}");
            }
        }

19 Source : MemAnalyzerTests.cs
with GNU Lesser General Public License v3.0
from Alois-xx

int StartMemreplacedyzer(string args, out string output)
        {
            string dir = Program.GetToolDeployDirectory();
            // delete old baseline which is deployed there. Otherwise we might test for x64 targets 
            // an old version.
            if( Directory.Exists(dir))
            {
                foreach(var file in Directory.GetFiles(dir, "*.*"))
                {
                    File.Delete(file);
                }
            }

            var info = new ProcessStartInfo("Memreplacedyzer.exe", args)
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true,
            };

            var p = Process.Start(info);
            output = p.StandardOutput.ReadToEnd();
            p.WaitForExit();

            return p.ExitCode;
        }

19 Source : Program.cs
with GNU General Public License v3.0
from Alois-xx

static void StartReg(string cmdLine)
        {
            var proc = new ProcessStartInfo("reg.exe", cmdLine)
            {
                UseShellExecute = false,
                RedirectStandardOutput = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                CreateNoWindow = true
            };
            var p = Process.Start(proc);
            Console.WriteLine($"Reg.exe Output from command {cmdLine}");
            Console.WriteLine(p.StandardOutput.Read());
            p.WaitForExit();
        }

19 Source : Program.cs
with GNU Lesser General Public License v3.0
from Alois-xx

private void RestartWithx64()
        {
            if( Environment.Is64BitProcess)
            {
                return;
            }

            if( IsChild )
            {
                Console.WriteLine("Recursion detected. Do not start any further child process. Please file an issue at https://github.com/Alois-xx/Memreplacedyzer/issues");
                return;
            }

            // If csv output file was already opened close it to allow child process to write to it.
            if (OutputStringWriter.CsvOutput == true)
            {
                OutputStringWriter.Output.Close();
                OutputStringWriter.Output = Console.Out;
                OutputStringWriter.CsvOutput = false;
            }

            string exe = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Memreplacedyzerx64.exe");

            // if -debug is specified do not deploy the exe into AppData. Instead start it from the location where where the main exe is located
            if( !IsDebug )
            {
                string appDir = GetToolDeployDirectory();
                Directory.CreateDirectory(appDir);
                exe = Path.Combine(appDir, "Memreplacedyzerx64.exe");
            }

            if (!File.Exists(exe))
            {
                File.WriteAllBytes(exe, Binaries.Memreplacedyzerx64);
                // Deploy app.config
                File.WriteAllText(exe + ".config", Binaries.App);
            }

            DebugPrinter.Write("Starting x64 child {0}", exe);
            ProcessStartInfo info = new ProcessStartInfo(exe, GetQuotedArgs() + " -child")
            {
                UseShellExecute = false,
                WindowStyle = ProcessWindowStyle.Hidden,
                CreateNoWindow = true,
                RedirectStandardOutput = true
            };
            var p = Process.Start(info);

            Console.CancelKeyPress += (a, b) => p.Kill();

            string output = null;
            while( (output =  p.StandardOutput.ReadLine()) != null )
            {
                Console.WriteLine(output);
            }
            p.WaitForExit();
            DebugPrinter.Write($"Setting return code from x64 process {p.ExitCode} to our own return code.");
            ReturnCode = p.ExitCode;
        }

19 Source : CertificateStorageManager.cs
with GNU General Public License v3.0
from aloopkin

public void ImportPFXIntoKSP(string KSP)
        {
            try {
                Process process = new Process();
                process.StartInfo.FileName = @"c:\Windows\System32\certutil.exe";
                process.StartInfo.Arguments = $"-importPFX -p {AuthenticatedPFX.PfxPreplacedword} -csp \"{KSP}\" -f My \"{AuthenticatedPFX.PfxFullPath}\"";
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.CreateNoWindow = true;
                process.Start();
                string output = "";
                while (!process.StandardOutput.EndOfStream) {
                    output += process.StandardOutput.ReadLine() + "\n";
                }
                process.WaitForExit();
                logger.Debug(output);
                if (output.Contains("FAILED")) {
                    logger.Error($"Impossible to import certificate into KSP {KSP}: {output}");
                } else {
                    logger.Info($"Successfully imported certificate into KSP {KSP}");
                }
            } catch (Exception e) {
                logger.Error($"Impossible to import certificate into KSP {KSP}: {e.Message}");
            }
        }

19 Source : ParquetMrIntegrationTest.cs
with MIT License
from aloneguid

private static string ExecAndGetOutput(string fileName, string arguments)
      {
         var psi = new ProcessStartInfo
         {
            FileName = fileName,
            Arguments = arguments,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true
         };

         var proc = new Process { StartInfo = psi };

         if (!proc.Start())
            return null;

         var so = new StringBuilder();
         var se = new StringBuilder();

         while (!proc.StandardOutput.EndOfStream)
         {
            string line = proc.StandardOutput.ReadLine();
            so.AppendLine(line);
         }

         while(!proc.StandardError.EndOfStream)
         {
            string line = proc.StandardError.ReadLine();
            se.AppendLine(line);
         }

         proc.WaitForExit();

         if(proc.ExitCode != 0)
         {
            throw new Exception("process existed with code " + proc.ExitCode + ", error: " + se.ToString());
         }

         return so.ToString().Trim();
      }

19 Source : RatAttack.cs
with GNU General Public License v3.0
from alterNERDtive

private static void Context_EDSM_GetNearestCMDR(dynamic vaProxy)
        {
            int caseNo = vaProxy.GetInt("~caseNo") ?? throw new ArgumentNullException("~caseNo");
            string cmdrList = vaProxy.GetText("~cmdrs") ?? throw new ArgumentNullException("~cmdrs");
            string[] cmdrs = cmdrList.Split(';');
            if (cmdrs.Length == 0)
            {
                throw new ArgumentNullException("~cmdrs");
            }
            string system = CaseList[caseNo]?.System ?? throw new ArgumentException($"Case #{caseNo} has no system information", "~caseNo");

            string path = $@"{vaProxy.SessionState["VA_SOUNDS"]}\Scripts\edsm-getnearest.exe";
            string arguments = $@"--short --text --system ""{system}"" ""{string.Join(@""" """, cmdrs)}""";

            Process p = PythonProxy.SetupPythonScript(path, arguments);

            p.Start();
            string stdout = p.StandardOutput.ReadToEnd();
            string stderr = p.StandardError.ReadToEnd();
            p.WaitForExit();

            string message = stdout;
            string? errorMessage = null;
            bool error = true;

            switch (p.ExitCode)
            {
                case 0:
                    error = false;
                    Log.Info(message);
                    break;
                case 1: // CMDR not found, Server Error, Api Exception (jeez, what a mess did I make there?)
                    error = true;
                    Log.Error(message);
                    break;
                case 2: // System not found
                    error = true;
                    Log.Warn(message);
                    break;
                default:
                    error = true;
                    Log.Error(stderr);
                    errorMessage = "Unrecoverable error in plugin.";
                    break;

            }

            vaProxy.SetText("~message", message);
            vaProxy.SetBoolean("~error", error);
            vaProxy.SetText("~errorMessage", errorMessage);
            vaProxy.SetInt("~exitCode", p.ExitCode);
        }

19 Source : SpanshAttack.cs
with GNU General Public License v3.0
from alterNERDtive

private static void Context_Spansh_Nearestsystem(dynamic vaProxy)
        {
            int x = vaProxy.GetInt("~x") ?? throw new ArgumentNullException("~x");
            int y = vaProxy.GetInt("~y") ?? throw new ArgumentNullException("~y");
            int z = vaProxy.GetInt("~z") ?? throw new ArgumentNullException("~z");

            string path = $@"{vaProxy.SessionState["VA_SOUNDS"]}\Scripts\spansh.exe";
            string arguments = $@"nearestsystem --parsable {x} {y} {z}";

            Process p = PythonProxy.SetupPythonScript(path, arguments);

            Dictionary<char, decimal> coords = new Dictionary<char, decimal> { { 'x', 0 }, { 'y', 0 }, { 'z', 0 } };
            string system = "";
            decimal distance = 0;
            bool error = false;
            string errorMessage = "";

            p.Start();
            string stdout = p.StandardOutput.ReadToEnd();
            string stderr = p.StandardError.ReadToEnd();
            p.WaitForExit();
            switch (p.ExitCode)
            {
                case 0:
                    string[] stdoutExploded = stdout.Split('|');
                    system = stdoutExploded[0];
                    distance = decimal.Parse(stdoutExploded[2]);
                    string[] stdoutCoords = stdoutExploded[1].Split(',');
                    coords['x'] = decimal.Parse(stdoutCoords[0]);
                    coords['y'] = decimal.Parse(stdoutCoords[1]);
                    coords['z'] = decimal.Parse(stdoutCoords[2]);
                    Log.Info($"Nearest system to ({x}, {y}, {z}): {system} ({coords['x']}, {coords['y']}, {coords['z']}), distance: {distance} ly");
                    break;
                case 1:
                    error = true;
                    errorMessage = stdout;
                    Log.Error(errorMessage);
                    break;
                default:
                    error = true;
                    Log.Error(stderr);
                    errorMessage = "Unrecoverable error in plugin.";
                    break;
            }

            vaProxy.SetText("~system", system);
            vaProxy.SetDecimal("~x", coords['x']);
            vaProxy.SetDecimal("~y", coords['y']);
            vaProxy.SetDecimal("~z", coords['z']);
            vaProxy.SetDecimal("~distance", distance);
            vaProxy.SetBoolean("~error", error);
            vaProxy.SetText("~errorMessage", errorMessage);
            vaProxy.SetInt("~exitCode", p.ExitCode);
        }

19 Source : SpanshAttack.cs
with GNU General Public License v3.0
from alterNERDtive

private static void Context_Spansh_SytemExists(dynamic vaProxy)
        {
            string system = vaProxy.GetText("~system") ?? throw new ArgumentNullException("~system");

            string path = $@"{vaProxy.SessionState["VA_SOUNDS"]}\Scripts\spansh.exe";
            string arguments = $@"systemexists ""{system}""";

            Process p = PythonProxy.SetupPythonScript(path, arguments);

            bool exists = true;
            bool error = false;
            string errorMessage = "";

            p.Start();
            string stdout = p.StandardOutput.ReadToEnd();
            string stderr = p.StandardError.ReadToEnd();
            p.WaitForExit();
            switch (p.ExitCode)
            {
                case 0:
                    Log.Info($@"System ""{system}"" found in Spansh’s DB");
                    break;
                case 1:
                    error = true;
                    errorMessage = stdout;
                    Log.Error(errorMessage);
                    break;
                case 3:
                    exists = false;
                    Log.Info($@"System ""{system}"" not found in Spansh’s DB");
                    break;
                default:
                    error = true;
                    Log.Error(stderr);
                    errorMessage = "Unrecoverable error in plugin.";
                    break;
            }

            vaProxy.SetBoolean("~systemExists", exists);
            vaProxy.SetBoolean("~error", error);
            vaProxy.SetText("~errorMessage", errorMessage);
            vaProxy.SetInt("~exitCode", p.ExitCode);
        }

19 Source : base.cs
with GNU General Public License v3.0
from alterNERDtive

private static void Context_EDSM_BodyCount(dynamic vaProxy)
        {
            string system = vaProxy.GetText("~system") ?? throw new ArgumentNullException("~system");

            string path = $@"{vaProxy.SessionState["VA_SOUNDS"]}\scripts\explorationtools.exe";
            string arguments = $@"bodycount ""{system}""";

            Process p = PythonProxy.SetupPythonScript(path, arguments);

            int bodyCount = 0;
            bool error = false;
            string errorMessage = "";

            p.Start();
            string stdout = p.StandardOutput.ReadToEnd();
            string stderr = p.StandardError.ReadToEnd();
            p.WaitForExit();
            switch (p.ExitCode)
            {
                case 0:
                    bodyCount = int.Parse(stdout);
                    Log.Info($"EDSM body count for {system}: {bodyCount}");
                    break;
                case 1:
                    error = true;
                    Log.Error(stdout);
                    errorMessage = stdout;
                    break;
                case 2:
                    error = true;
                    Log.Notice($@"System ""{system}"" not found on EDSM");
                    errorMessage = stdout;
                    break;
                default:
                    error = true;
                    Log.Error(stderr);
                    errorMessage = "Unrecoverable error in plugin.";
                    break;
            }

            vaProxy.SetInt("~bodyCount", bodyCount);
            vaProxy.SetBoolean("~error", error);
            vaProxy.SetText("~errorMessage", errorMessage);
            vaProxy.SetInt("~exitCode", p.ExitCode);
        }

19 Source : base.cs
with GNU General Public License v3.0
from alterNERDtive

private static void Context_EDSM_DistanceBetween(dynamic vaProxy)
        {
            string fromSystem = vaProxy.GetText("~fromSystem") ?? throw new ArgumentNullException("~fromSystem");
            string toSystem = vaProxy.GetText("~toSystem") ?? throw new ArgumentNullException("~toSystem");
            int roundTo = vaProxy.GetInt("~roundTo") ?? 2;

            string path = $@"{vaProxy.SessionState["VA_SOUNDS"]}\Scripts\explorationtools.exe";
            string arguments = $@"distancebetween --roundto {roundTo} ""{fromSystem}"" ""{toSystem}""";

            Process p = PythonProxy.SetupPythonScript(path, arguments);

            decimal distance = 0;
            bool error = false;
            string errorMessage = "";

            p.Start();
            string stdout = p.StandardOutput.ReadToEnd();
            string stderr = p.StandardError.ReadToEnd();
            p.WaitForExit();
            switch (p.ExitCode)
            {
                case 0:
                    distance = decimal.Parse(stdout);
                    Log.Info($"{fromSystem} → {toSystem}: {distance} ly");
                    break;
                case 1:
                case 2:
                    error = true;
                    Log.Error(stdout);
                    errorMessage = stdout;
                    break;
                default:
                    error = true;
                    Log.Error(stderr);
                    errorMessage = "Unrecoverable error in plugin.";
                    break;

            }

            vaProxy.SetDecimal("~distance", distance);
            vaProxy.SetBoolean("~error", error);
            vaProxy.SetText("~errorMessage", errorMessage);
            vaProxy.SetInt("~exitCode", p.ExitCode);
        }

19 Source : base.cs
with GNU General Public License v3.0
from alterNERDtive

private static void Context_Spansh_OutdatedStations(dynamic vaProxy)
        {
            string system = vaProxy.GetText("~system") ?? throw new ArgumentNullException("~system");
            int minage = vaProxy.GetInt("~minage") ?? throw new ArgumentNullException("~minage");

            string path = $@"{vaProxy.SessionState["VA_SOUNDS"]}\Scripts\spansh.exe";
            string arguments = $@"oldstations --system ""{system}"" --minage {minage}";

            Process p = PythonProxy.SetupPythonScript(path, arguments);


            p.Start();
            string stdout = p.StandardOutput.ReadToEnd();
            string stderr = p.StandardError.ReadToEnd();
            p.WaitForExit();

            string message = stdout;
            string? errorMessage = null;
            bool error = true;

            switch (p.ExitCode)
            {
                case 0:
                    error = false;
                    Log.Notice($"Outdated stations for {system}: {message}");
                    break;
                case 1:
                    error = true;
                    Log.Error(message);
                    break;
                case 3:
                    error = true;
                    Log.Info($@"No outdated stations found for ""{system}""");
                    break;
                default:
                    error = true;
                    Log.Error(stderr);
                    errorMessage = "Unrecoverable error in plugin.";
                    break;

            }

            vaProxy.SetText("~message", message);
            vaProxy.SetBoolean("~error", error);
            vaProxy.SetText("~errorMessage", errorMessage);
            vaProxy.SetInt("~exitCode", p.ExitCode);
        }

19 Source : ConverterService.cs
with GNU General Public License v3.0
from alxnbl

public string ConvertDocxToMd(Page page, string inputFilePath, string resourceFolderPath, int sectionTreeLevel)
        {
           
            var mdFilePath = Path.Combine("tmp", page.replacedleWithNoInvalidChars + ".md");

            var arguments = $"\"{Path.GetFullPath(inputFilePath)}\"  " +
                            $"--to gfm " +
                            $"-o \"{Path.GetFullPath(mdFilePath)}\" " +
                            $"--wrap=none " + // Mandatory to avoid random quote bloc to be added to markdown
                            $"--extract-media=\"tmp\"";

            var startInfo = new ProcessStartInfo
            {
                FileName = "pandoc.exe",
                Arguments = arguments,
                UseShellExecute = false,
                CreateNoWindow = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };


            Log.Debug($"{page.Id} : Start Pandoc");

            using (Process exeProcess = Process.Start(startInfo))
            {
                exeProcess.WaitForExit();

                if(exeProcess.ExitCode == 0)
                {
                    Log.Debug($"{page.Id} : Pandoc success");
                }
                else
                {
                    Log.Error($"{page.Id} : Pandoc error");
                    var pandocError = exeProcess.StandardError.ReadToEnd();
                    Log.Error("Pandoc error output: {0}", pandocError);
                }


                if (_appSettings.Debug)
                {
                    Log.Debug($"Pandoc output: {exeProcess.StandardOutput.ReadToEnd()}");
                }
            }

            var mdFileContent = File.ReadAllText(mdFilePath);

            if (!_appSettings.Debug)
                File.Delete(inputFilePath);

            return mdFileContent;
        }

19 Source : TestHelper.cs
with GNU General Public License v3.0
from alxnbl

public static (string output, int exitCode, string exportResult) RunExporter(string format, string notebook, string section, string page)
        {
            string args = $"-f \"{format}\" -n \"{notebook}\" -s \"{section}\" -p \"{page}\" --no-input";

            var startInfo = new ProcessStartInfo
            {
                FileName = "alxnbl.OneNoteMdExporter.exe",
                Arguments = args,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };

            string output = string.Empty;

            using (Process exeProcess = Process.Start(startInfo))
            {
                exeProcess.WaitForExit();

                if (exeProcess.ExitCode != 0)
                {
                    output = exeProcess.StandardError.ReadToEnd();
                }
                else
                {
                    output = exeProcess.StandardOutput.ReadToEnd();
                }

                string exportResult = format == "1" ? TestHelper.GetMdExportResult(notebook, section, page) : "";

                return (output, exeProcess.ExitCode, exportResult);
            }

        }

19 Source : ModPacker.cs
with GNU General Public License v3.0
from AM2R-Community-Developers

private void CreateModPack(string operatingSystem, string input, string output)
        {
            LoadProfileParameters(operatingSystem);

            // Cleanup in case of previous errors
            if (Directory.Exists(Path.GetTempPath() + "\\AM2RModPacker"))
            {
                Directory.Delete(Path.GetTempPath() + "\\AM2RModPacker", true);
            }

            // Create temp work folders
            string tempPath = "",
                   tempOriginalPath = "",
                   tempModPath = "",
                   tempProfilePath = "";

            // We might not have permission to access to the temp directory, so we need to catch the exception.
            try
            {
                tempPath = Directory.CreateDirectory(Path.GetTempPath() + "\\AM2RModPacker").FullName;
                tempOriginalPath = Directory.CreateDirectory(tempPath + "\\original").FullName;
                tempModPath = Directory.CreateDirectory(tempPath + "\\mod").FullName;
                tempProfilePath = Directory.CreateDirectory(tempPath + "\\profile").FullName;
            }
            catch (System.Security.SecurityException)
            {
                MessageBox.Show("Could not create temp directory! Please run the application with administrator rights.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                AbortPatch();

                return;
            }

            // Extract 1.1 and modded AM2R to their own directories in temp work
            ZipFile.ExtractToDirectory(originalPath, tempOriginalPath);
            ZipFile.ExtractToDirectory(input, tempModPath);

            if (Directory.Exists(tempModPath + "\\AM2R"))
                tempModPath += "\\AM2R";

            // Verify 1.1 with an MD5. If it does not match, exit cleanly and provide a warning window.
            try
            {
                string newMD5 = CalculateMD5(tempOriginalPath + "\\data.win");

                if (newMD5 != ORIGINAL_MD5)
                {
                    // Show error box
                    MessageBox.Show("1.1 data.win does not meet MD5 checksum! Mod packaging aborted.\n1.1 MD5: " + ORIGINAL_MD5 + "\nYour MD5: " + newMD5, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    AbortPatch();

                    return;
                }
            }
            catch (FileNotFoundException)
            {
                // Show error message
                MessageBox.Show("data.win not found! Are you sure you selected AM2R 1.1? Mod packaging aborted.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                AbortPatch();

                return;
            }

            // Create AM2R.exe and data.win patches
            if (profile.OperatingSystem == "Windows")
            {
                if (!File.Exists(tempModPath + "/AM2R.exe"))
                {
                    var result = MessageBox.Show("Modded game not found, make sure it's not placed in any subfolders.\nCreated profile will likely not be installable, are you sure you want to continue?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result != DialogResult.Yes)
                        AbortPatch();
                }

                if (File.Exists(tempModPath + "profile.xml"))
                {
                    var result = MessageBox.Show("profile.xml found. This file is used by the AM2RLauncher to determine profile stats and its inclusion may make the profile uninstallable. Are you sure you want to continue?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result != DialogResult.Yes)
                        AbortPatch();
                }

                if (profile.UsesYYC)
                {
                    CreatePatch(tempOriginalPath + "\\data.win", tempModPath + "\\AM2R.exe", tempProfilePath + "\\AM2R.xdelta");
                }
                else
                {
                    CreatePatch(tempOriginalPath + "\\data.win", tempModPath + "\\data.win", tempProfilePath + "\\data.xdelta");

                    CreatePatch(tempOriginalPath + "\\AM2R.exe", tempModPath + "\\AM2R.exe", tempProfilePath + "\\AM2R.xdelta");
                }
            }
            else if (profile.OperatingSystem == "Linux")
            {
                string runnerName = File.Exists(tempModPath + "\\" + "AM2R") ? "AM2R" : "runner";

                if (!File.Exists(tempModPath + "/" + runnerName))
                {
                    var result = MessageBox.Show("Modded Linux game not found, make sure it's not placed in any subfolders.\nCreated profile will likely not be installable, are you sure you want to continue?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result != DialogResult.Yes)
                        AbortPatch();
                }

                if (File.Exists(tempModPath + "profile.xml"))
                {
                    var result = MessageBox.Show("profile.xml found. This file is used by the AM2RLauncher to determine profile stats and its inclusion may make the profile uninstallable. Are you sure you want to continue?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result != DialogResult.Yes)
                        AbortPatch();
                }

                CreatePatch(tempOriginalPath + "\\data.win", tempModPath + "\\replacedets\\game.unx", tempProfilePath + "\\game.xdelta");
                CreatePatch(tempOriginalPath + "\\AM2R.exe", tempModPath + "\\" + runnerName, tempProfilePath + "\\AM2R.xdelta");
            }

            // Create game.droid patch and wrapper if Android is supported
            if (profile.Android)
            {
                string tempAndroid = Directory.CreateDirectory(tempPath + "\\android").FullName;

                // Extract APK 
                // - java -jar apktool.jar d "%~dp0AM2RWrapper_old.apk"

                // Process startInfo
                ProcessStartInfo procStartInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    WorkingDirectory = tempAndroid,
                    Arguments = "/C java -jar \"" + localPath + "\\utilities\\android\\apktool.jar\" d -f -o \"" + tempAndroid + "\" \"" + apkPath + "\"",
                    UseShellExecute = false,
                    CreateNoWindow = true
                };

                // Run process
                using (Process proc = new Process { StartInfo = procStartInfo })
                {
                    proc.Start();

                    proc.WaitForExit();
                }

                // Create game.droid patch
                CreatePatch(tempOriginalPath + "\\data.win", tempAndroid + "\\replacedets\\game.droid", tempProfilePath + "\\droid.xdelta");

                // Delete excess files in APK

                // Create whitelist
                string[] whitelist = { "splash.png", "portrait_splash.png" };

                // Get directory
                DirectoryInfo androidreplacedets = new DirectoryInfo(tempAndroid + "\\replacedets");

                


                // Delete files
                foreach (FileInfo file in androidreplacedets.GetFiles())
                {
                    if (file.Name.EndsWith(".ini") && file.Name != "modifiers.ini")
                    {
                        if (File.Exists(tempProfilePath + "\\AM2R.ini"))
                        {
                            // This shouldn't be a problem... normally...
                            File.Delete(tempProfilePath + "\\AM2R.ini");
                        }
                        File.Copy(file.FullName, tempProfilePath + "\\AM2R.ini");
                    }

                    if (!whitelist.Contains(file.Name))
                    {
                        File.Delete(file.FullName);
                    }
                }

                foreach (DirectoryInfo dir in androidreplacedets.GetDirectories())
                {
                    Directory.Delete(dir.FullName, true);
                }

                // Create wrapper

                // Process startInfo
                // - java -jar apktool.jar b "%~dp0AM2RWrapper_old" -o "%~dp0AM2RWrapper.apk"
                ProcessStartInfo procStartInfo2 = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    WorkingDirectory = tempAndroid,
                    Arguments = "/C java -jar \"" + localPath + "\\utilities\\android\\apktool.jar\" b -f \"" + tempAndroid + "\" -o \"" + tempProfilePath + "\\AM2RWrapper.apk\"",
                    UseShellExecute = false,
                    CreateNoWindow = true
                };

                // Run process
                using (Process proc = new Process { StartInfo = procStartInfo2 })
                {
                    proc.Start();

                    proc.WaitForExit();
                }

                string tempAndroidProfilePath = tempProfilePath + "\\android";
                Directory.CreateDirectory(tempAndroidProfilePath);

                File.Move(tempProfilePath + "\\AM2RWrapper.apk", tempAndroidProfilePath + "\\AM2RWrapper.apk");
                if (File.Exists(tempProfilePath + "\\AM2R.ini"))
                    File.Move(tempProfilePath + "\\AM2R.ini", tempAndroidProfilePath + "\\AM2R.ini");
            }

            // Copy datafiles (exclude .ogg if custom music is not selected)

            DirectoryInfo dinfo = new DirectoryInfo(tempModPath);
            if (profile.OperatingSystem == "Linux")
                dinfo = new DirectoryInfo(tempModPath + "\\replacedets");

            Directory.CreateDirectory(tempProfilePath + "\\files_to_copy");

            if (profile.UsesCustomMusic)
            {
                // Copy files, excluding the blacklist
                CopyFilesRecursive(dinfo, DATAFILES_BLACKLIST, tempProfilePath + "\\files_to_copy");
            }
            else
            {
                // Get list of 1.1's music files
                string[] musFiles = Directory.GetFiles(tempOriginalPath, "*.ogg").Select(file => Path.GetFileName(file)).ToArray();

                if (profile.OperatingSystem == "Linux")
                    musFiles = Directory.GetFiles(tempOriginalPath, "*.ogg").Select(file => Path.GetFileName(file).ToLower()).ToArray();


                // Combine musFiles with the known datafiles for a blacklist
                string[] blacklist = musFiles.Concat(DATAFILES_BLACKLIST).ToArray();

                // Copy files, excluding the blacklist
                CopyFilesRecursive(dinfo, blacklist, tempProfilePath + "\\files_to_copy");
            }

            // Export profile as XML
            string xmlOutput = Serializer.Serialize<ModProfileXML>(profile);
            File.WriteAllText(tempProfilePath + "\\profile.xml", xmlOutput);

            // Compress temp folder to .zip
            if (File.Exists(output))
            {
                File.Delete(output);
            }

            ZipFile.CreateFromDirectory(tempProfilePath, output);

            // Delete temp folder
            Directory.Delete(tempPath, true);
        }

19 Source : ModPacker.cs
with GNU General Public License v3.0
from AM2R-Community-Developers

private void CreatePatch(string original, string modified, string output)
        {
            // Specify process start info
            ProcessStartInfo parameters = new ProcessStartInfo
            {
                FileName = localPath + "\\utilities\\xdelta\\xdelta3.exe",
                WorkingDirectory = localPath,
                UseShellExecute = false,
                CreateNoWindow = true,
                Arguments = "-f -e -s \"" + original + "\" \"" + modified + "\" \"" + output + "\""
            };

            // Launch process and wait for exit. using statement automatically disposes the object for us!
            using (Process proc = new Process { StartInfo = parameters })
            {
                proc.Start();

                proc.WaitForExit();
            }
        }

19 Source : frmMain.cs
with GNU General Public License v3.0
from amakvana

private async Task ProcessDependencies(string yuzuLocation)
        {
            ToggleControls(false);

            // create temp directory for downloads 
            string tempDir = yuzuLocation + "\\TempUpdate";
            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            // download vc++
            using (var wc = new WebClient())
            {
                wc.DownloadFileCompleted += (s, e) =>
                {
                    // install 
                    SetProgressLabelStatus("Installing Visual C++ 2019 ...");
                    using (var p = new Process())
                    {
                        p.StartInfo.FileName = tempDir + "\\vc_redist.x64.exe";
                        p.StartInfo.Arguments = "/install /quiet /norestart";
                        p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        p.Start();
                        p.WaitForExit();
                    }

                    // cleanup 
                    try
                    {
                        Directory.Delete(tempDir, true);
                    }
                    catch { }
                    SetProgressLabelStatus("Installed!");
                    ToggleControls(true);
                    pbarProgress.Value = 0;
                };
                wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
                SetProgressLabelStatus("Downloading Visual C++ 2019 ...");
                await wc.DownloadFileTaskAsync(new Uri("https://aka.ms/vs/16/release/vc_redist.x64.exe"), tempDir + "\\vc_redist.x64.exe");
            }
        }

19 Source : Guard.cs
with MIT License
from AmazingDM

protected void StopInstance()
        {
            try
            {
                if (Instance == null || Instance.HasExited) return;
                Instance.Kill();
                Instance.WaitForExit();
            }
            catch (Win32Exception e)
            {
                Logging.Error($"停止 {MainFile} 错误:\n" + e);
            }
            catch
            {
                // ignored
            }
        }

19 Source : Program.cs
with MIT License
from AmazingDM

public static void Main(string[] args)
        {
            var result = false;

            try
            {
                #region Check Arguments

                if (CurrentProcess.MainModule == null)
                {
                    Console.WriteLine("Current Process MainModule is null");
                    return;
                }

                if (args.Length != 3)
                {
                    Console.WriteLine("The program is not user-oriented\n此程序不是面向用户的");
                    return;
                }

                // arg0 port
                if (!int.TryParse(args[0], out var port))
                {
                    Console.WriteLine("arg0 Port Parse failed");
                    return;
                }

                var updateExtracted = true;
                // arg1 update File/Directory
                var updatePath = Path.GetFullPath(args[1]);
                if (File.Exists(updatePath))
                {
                    updateExtracted = false;
                }
                else if (!Directory.Exists(updatePath))
                {
                    Console.WriteLine("arg1 update file/directory Not found");
                    return;
                }

                // arg2 target Directory
                string targetPath;
                if (!File.Exists(Path.Combine(targetPath = Path.GetFullPath(args[2]), "Netch.exe")))
                {
                    Console.Write("arg2 Netch Directory doesn't seems right");
                    return;
                }

                #region if under target Directory,then rerun in temp directory

                if (UpdaterDirectory.StartsWith(targetPath))
                {
                    // Updater 在目标目录下
                    // 将程序复制到临时目录,传递参数
                    var tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                    var newUpdaterPath = Path.Combine(tempPath, UpdaterFriendlyName);
                    Directory.CreateDirectory(tempPath);
                    File.Copy(UpdaterFullName, newUpdaterPath);
                    Process.Start(new ProcessStartInfo
                    {
                        FileName = newUpdaterPath,
                        Arguments = $"{port} \"{updatePath}\" \"{targetPath}\"",
                        WorkingDirectory = tempPath,
                        UseShellExecute = false
                    });
                    result = true;
                    return;
                }

                #endregion

                #endregion

                /*Console.WriteLine("Waiting Attach");
                while (!Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }*/

                #region Send Netch Exit command

                Process[] _;
                if ((_ = Process.GetProcessesByName("Netch")).Any())
                {
                    Console.WriteLine("Found Netch process, Send exit command");
                    try
                    {
                        var udpClient = new UdpClient("127.0.0.1", port);
                        var sendBytes = Encoding.ASCII.GetBytes("Exit");
                        udpClient.Send(sendBytes, sendBytes.Length);
                    }
                    catch
                    {
                        Console.WriteLine("Send command failed");
                        return;
                    }

                    foreach (var proc in _)
                    {
                        try
                        {
                            proc.WaitForExit();
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                    }
                }

                #endregion

                var counter = 0;
                while (!TestFileFree(Path.Combine(targetPath, "Netch.exe")))
                {
                    // wait 5 sec
                    if (counter > 25)
                    {
                        Console.WriteLine("Waiting Netch exit timeout");
                        return;
                    }

                    Thread.Sleep(200);
                    counter++;
                }

                #region Update

                string extractPath = null;
                if (!updateExtracted)
                {
                    extractPath = Path.Combine(UpdaterDirectory, "extract");
                    Extract(updatePath, extractPath, true);

                    var netchExeFileInfo = FindFile("Netch.exe", extractPath);

                    if (netchExeFileInfo == null)
                    {
                        throw new Exception("Netch.exe not found in archive!");
                    }

                    updatePath = netchExeFileInfo.Directory.FullName;
                }

                MoveDirectory(updatePath, targetPath, true);

                try
                {
                    if (extractPath != null)
                        Directory.Delete(extractPath, true);
                }
                catch
                {
                    // ignored
                }

                #endregion

                #region Finished Update,Start Netch

                Console.WriteLine("Start Netch");
                Process.Start(new ProcessStartInfo
                {
                    FileName = Path.Combine(targetPath, "Netch.exe"),
                    UseShellExecute = true,
                });

                #endregion

                result = true;
            }
            catch (Exception e)
            {
                if (e is InvalidDataException)
                    Console.WriteLine("Archive file Broken");
                Console.WriteLine(e.ToString());
            }
            finally
            {
                if (!result)
                {
                    Console.WriteLine("Press any key to exit...");
                    Console.Read();
                }
            }
        }

19 Source : PortHelper.cs
with MIT License
from AmazingDM

private static void GetReservedPortRange(PortType portType, ref List<Range> targetList)
        {
            var lines = new List<string>();
            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "netsh",
                    Arguments = $" int ipv4 show excludedportrange {portType}",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                }
            };
            process.OutputDataReceived += (s, e) =>
            {
                if (e.Data != null) lines.Add(e.Data);
            };
            process.Start();
            process.BeginOutputReadLine();
            process.WaitForExit();

            var splitLine = false;
            foreach (var line in lines)
                if (!splitLine)
                {
                    if (line.StartsWith("-"))
                        splitLine = true;
                }
                else
                {
                    if (line == string.Empty)
                        break;

                    var value = line.Trim().Split(' ').Where(s => s != string.Empty).ToArray();

                    targetList.Add(new Range(ushort.Parse(value[0]), ushort.Parse(value[1])));
                }
        }

19 Source : TUNTAP.cs
with MIT License
from AmazingDM

public static void deltapall()
        {
            Logging.Info("卸载 TUN/TAP 适配器");
            var installProcess = new Process {StartInfo = {WindowStyle = ProcessWindowStyle.Hidden, FileName = Path.Combine("bin/tap-driver", "deltapall.bat")}};
            installProcess.Start();
            installProcess.WaitForExit();
            installProcess.Close();
        }

19 Source : TUNTAP.cs
with MIT License
from AmazingDM

public static void addtap()
        {
            Logging.Info("安装 TUN/TAP 适配器");
            //安装Tap Driver
            var installProcess = new Process {StartInfo = {WindowStyle = ProcessWindowStyle.Hidden, FileName = Path.Combine("bin/tap-driver", "addtap.bat")}};
            installProcess.Start();
            installProcess.WaitForExit();
            installProcess.Close();
        }

19 Source : Program.cs
with MIT License
from AmazingDM

private static void Extract(string archiveFileName, string destDirName, bool overwrite)
        {
            archiveFileName = Path.GetFullPath(archiveFileName);
            destDirName = Path.GetFullPath(destDirName);

            if (!File.Exists("7za.exe"))
                File.WriteAllBytes("7za.exe", Resources._7za);

            var argument = new StringBuilder();
            argument.Append($" x \"{archiveFileName}\" -o\"{destDirName}\" ");
            if (overwrite)
                argument.Append(" -y ");

            Process.Start(new ProcessStartInfo
            {
                UseShellExecute = false,
                WindowStyle = ProcessWindowStyle.Hidden,
                FileName = Path.GetFullPath("7za.exe"),
                Arguments = argument.ToString()
            })?.WaitForExit();
        }

19 Source : CrossPlatformOperations.cs
with GNU General Public License v3.0
from AM2R-Community-Developers

public static bool IsJavaInstalled()
        {
            string process = null;
            string arguments = null;

            if (currentPlatform.IsWinForms)
            {
                process = "cmd.exe";
                arguments = "/C java -version";
            }
            else if (currentPlatform.IsGtk)
            {
                process = "java";
                arguments = "-version";
            }

            ProcessStartInfo javaStart = new ProcessStartInfo();
            javaStart.FileName = process;
            javaStart.Arguments = arguments;
            javaStart.UseShellExecute = false;
            javaStart.CreateNoWindow = true;


            Process java = new Process();

            java.StartInfo = javaStart;

            //this is primarily for linux, but could be happening on windows as well
            try
            {
                java.Start();

                java.WaitForExit();
            }
            catch (System.ComponentModel.Win32Exception)
            {
                return false;
            }

            return java.ExitCode == 0;
            
        }

19 Source : CrossPlatformOperations.cs
with GNU General Public License v3.0
from AM2R-Community-Developers

public static bool CheckIfXdeltaIsInstalled()
        {
            string process = "xdelta3";
            string arguments = "-V";      

            ProcessStartInfo xdeltaStart = new ProcessStartInfo();
            xdeltaStart.FileName = process;
            xdeltaStart.Arguments = arguments;
            xdeltaStart.UseShellExecute = false;
            xdeltaStart.CreateNoWindow = true;


            Process xdelta = new Process();

            xdelta.StartInfo = xdeltaStart;

            try
            {
                xdelta.Start();

                xdelta.WaitForExit();
            }
            catch (System.ComponentModel.Win32Exception)
            {
                return false;
            }

            return xdelta.ExitCode == 0;
        }

19 Source : CrossPlatformOperations.cs
with GNU General Public License v3.0
from AM2R-Community-Developers

public static void ApplyXdeltaPatch(string original, string patch, string output)
        {
            // for *whatever reason* **sometimes** xdelta patching doesn't work, if output = original. So I'm fixing that here.
            string originalOutput = output;
            if (original == output)
                output = output += "_";

            string arguments = "-f -d -s \"" + original.Replace(CURRENTPATH + "/","") + "\" \"" + patch.Replace(CURRENTPATH + "/", "") + "\" \"" + output.Replace(CURRENTPATH + "/", "") + "\"";

            if (currentPlatform.IsWinForms)
            {
                // We want some fancy parameters for Windows because the terminal scares end users :(
                ProcessStartInfo parameters = new ProcessStartInfo
                {
                    FileName = CURRENTPATH + "/PatchData/utilities/xdelta/xdelta3.exe",
                    WorkingDirectory = CURRENTPATH + "",
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    Arguments = arguments
                };

                using (Process proc = new Process { StartInfo = parameters })
                {
                    proc.Start();

                    proc.WaitForExit();
                }
            }
            else if (currentPlatform.IsGtk)
            {
                ProcessStartInfo parameters = new ProcessStartInfo
                {
                    FileName = "xdelta3",
                    Arguments = arguments,
                    WorkingDirectory = CURRENTPATH
                };

                using (Process proc = Process.Start(parameters))
                {
                    proc.WaitForExit();
                }
            }

            if (originalOutput != output && File.Exists(output))
            {
                File.Delete(originalOutput);
                File.Move(output, originalOutput);
            }
        }

19 Source : SystemsHelper.cs
with MIT License
from Amine-Smahi

private static void StartProcessWithResult(Process process)
        {
            var result = string.Empty;
            process.Start();
            result += process.StandardOutput.ReadToEnd();
            result += process.StandardError.ReadToEnd();
            process.WaitForExit();
            NotificationsHelper.DisplayMessage(Messages.DisplayProcessExecutionResult(result));
        }

19 Source : TestBase.cs
with Apache License 2.0
from AmpScm

public string RunCommand( string command, string args )
        {
            Process proc = new Process();
            proc.StartInfo.FileName = command;
            proc.StartInfo.Arguments = args;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.UseShellExecute = false;

            proc.Start();

            //Console.WriteLine( proc.MainModule.FileName );

            ProcessReader outreader = new ProcessReader( proc.StandardOutput );
            ProcessReader errreader = new ProcessReader( proc.StandardError );
            outreader.Start();
            errreader.Start();

            proc.WaitForExit();

            outreader.Wait();
            errreader.Wait();

            if ( proc.ExitCode != 0 )
                throw new ApplicationException( "command exit code was " + 
                    proc.ExitCode.ToString() +
                    Environment.NewLine + errreader.Output + Environment.NewLine +
                    "Command was " + 
                    proc.StartInfo.FileName + " " + proc.StartInfo.Arguments );


            // normalize newlines
            string[] lines = Regex.Split( outreader.Output, @"\r?\n" );  
            return String.Join( Environment.NewLine, lines );
        }

19 Source : BuildDeployTools.cs
with MIT License
from anderm

public static string CalcMSBuildPath(string msBuildVersion)
        {
            if (msBuildVersion.Equals("14.0"))
            {
                using (Microsoft.Win32.RegistryKey key =
                    Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
                        string.Format(@"Software\Microsoft\MSBuild\ToolsVersions\{0}", msBuildVersion)))
                {
                    if (key == null)
                    {
                        return null;
                    }

                    var msBuildBinFolder = (string)key.GetValue("MSBuildToolsPath");
                    return Path.Combine(msBuildBinFolder, "msbuild.exe");
                }
            }

            // For MSBuild 15+ we should to use vswhere to give us the correct instance
            string output = @"/C cd ""%ProgramFiles(x86)%\Microsoft Visual Studio\Installer"" && vswhere -version " + msBuildVersion + " -products * -requires Microsoft.Component.MSBuild -property installationPath";

            var vswherePInfo = new System.Diagnostics.ProcessStartInfo
            {
                FileName = "cmd.exe",
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                Arguments = output
            };

            using (var vswhereP = new System.Diagnostics.Process())
            {
                vswhereP.StartInfo = vswherePInfo;
                vswhereP.Start();
                output = vswhereP.StandardOutput.ReadToEnd();
                vswhereP.WaitForExit();
                vswhereP.Close();
                vswhereP.Dispose();
            }

            output = output + @"\MSBuild\" + msBuildVersion + @"\Bin\MSBuild.exe";
            output = output.Replace(Environment.NewLine, "");
            return output;
        }

19 Source : BuildDeployTools.cs
with MIT License
from anderm

public static bool RestoreNugetPackages(string nugetPath, string storePath)
        {
            var nugetPInfo = new System.Diagnostics.ProcessStartInfo
            {
                FileName = nugetPath,
                CreateNoWindow = true,
                UseShellExecute = false,
                Arguments = "restore \"" + storePath + "/project.json\""
            };

            using (var nugetP = new System.Diagnostics.Process())
            {
                nugetP.StartInfo = nugetPInfo;
                nugetP.Start();
                nugetP.WaitForExit();
                nugetP.Close();
                nugetP.Dispose();
            }

            return File.Exists(storePath + "\\project.lock.json");
        }

19 Source : BuildDeployTools.cs
with MIT License
from anderm

public static bool BuildAppxFromSLN(string productName, string msBuildVersion, bool forceRebuildAppx, string buildConfig, string buildDirectory, bool incrementVersion, bool showDialog = true)
        {
            EditorUtility.DisplayProgressBar("Build AppX", "Building AppX Package...", 0);
            string slnFilename = Path.Combine(buildDirectory, PlayerSettings.productName + ".sln");

            if (!File.Exists(slnFilename))
            {
                Debug.LogError("Unable to find Solution to build from!");
                EditorUtility.ClearProgressBar();
                return false;
            }

            // Get and validate the msBuild path...
            var vs = CalcMSBuildPath(msBuildVersion);

            if (!File.Exists(vs))
            {
                Debug.LogError("MSBuild.exe is missing or invalid (path=" + vs + "). Note that the default version is " + DefaultMSBuildVersion);
                EditorUtility.ClearProgressBar();
                return false;
            }

            // Get the path to the NuGet tool
            string unity = Path.GetDirectoryName(EditorApplication.applicationPath);
            System.Diagnostics.Debug.replacedert(unity != null, "unity != null");
            string storePath = Path.GetFullPath(Path.Combine(Path.Combine(Application.dataPath, ".."), buildDirectory));
            string solutionProjectPath = Path.GetFullPath(Path.Combine(storePath, productName + @".sln"));

            // Bug in Unity editor that doesn't copy project.json and project.lock.json files correctly if solutionProjectPath is not in a folder named UWP.
            if (!File.Exists(storePath + "\\project.json"))
            {
                File.Copy(unity + @"\Data\PlaybackEngines\MetroSupport\Tools\project.json", storePath + "\\project.json");
            }

            string nugetPath = Path.Combine(unity, @"Data\PlaybackEngines\MetroSupport\Tools\NuGet.exe");

            // Before building, need to run a nuget restore to generate a json.lock file. Failing to do
            // this breaks the build in VS RTM
            if (!RestoreNugetPackages(nugetPath, storePath) ||
                !RestoreNugetPackages(nugetPath, storePath + "\\" + productName) ||
                EditorUserBuildSettings.wsaGenerateReferenceProjects && !RestoreNugetPackages(nugetPath, storePath + "/GeneratedProjects/UWP/replacedembly-CSharp") ||
                EditorUserBuildSettings.wsaGenerateReferenceProjects && !RestoreNugetPackages(nugetPath, storePath + "/GeneratedProjects/UWP/replacedembly-CSharp-firstpreplaced"))
            {
                Debug.LogError("Failed to restore nuget packages");
                EditorUtility.ClearProgressBar();
                return false;
            }

            EditorUtility.DisplayProgressBar("Build AppX", "Building AppX Package...", 25);

            // Ensure that the generated .appx version increments by modifying
            // Package.appxmanifest
            if (incrementVersion)
            {
                IncrementPackageVersion();
            }

            // Now do the actual build
            var pInfo = new System.Diagnostics.ProcessStartInfo
            {
                FileName = vs,
                CreateNoWindow = false,
                Arguments = string.Format("\"{0}\" /t:{2} /p:Configuration={1} /p:Platform=x86 /verbosity:m",
                    solutionProjectPath,
                    buildConfig,
                    forceRebuildAppx ? "Rebuild" : "Build")
            };

            // Uncomment out to debug by copying into command window
            //Debug.Log("\"" + vs + "\"" + " " + pInfo.Arguments);

            var process = new System.Diagnostics.Process { StartInfo = pInfo };

            try
            {
                if (!process.Start())
                {
                    Debug.LogError("Failed to start Cmd process!");
                    EditorUtility.ClearProgressBar();
                    return false;
                }

                process.WaitForExit();

                EditorUtility.ClearProgressBar();

                if (process.ExitCode == 0 &&
                    showDialog &&
                    !EditorUtility.DisplayDialog("Build AppX", "AppX Build Successful!", "OK", "Open Project Folder"))
                {
                    System.Diagnostics.Process.Start("explorer.exe", "/select," + storePath);
                }

                if (process.ExitCode != 0)
                {
                    Debug.LogError("MSBuild error (code = " + process.ExitCode + ")");
                    EditorUtility.DisplayDialog(PlayerSettings.productName + " build Failed!", "Failed to build appx from solution. Error code: " + process.ExitCode, "OK");
                    return false;
                }

                process.Close();
                process.Dispose();

            }
            catch (Exception e)
            {
                Debug.LogError("Cmd Process EXCEPTION: " + e);
                EditorUtility.ClearProgressBar();
                return false;
            }

            return true;
        }

19 Source : AspNetToNgRedirector.cs
with MIT License
from andfomin

private static bool IsNgServerPortAvailable(int ngServerPort)
        {
            // Be optimistic. If the check fails, the CLI will report the conflict anyway.
            bool isNgServerPortAvailable = true;
            // If the value is 0, "ng serve" tries to start on 4200, 4201, 4202, 4203, and so on, until it finds an available port.
            if (ngServerPort > 0)
            {
                using (var netstatProcess = new Process())
                {
                    netstatProcess.StartInfo.FileName = "cmd.exe";
                    netstatProcess.StartInfo.Arguments = $"/c netstat.exe -a -n -p TCP | findstr LISTENING | findstr :{ngServerPort}";
                    netstatProcess.StartInfo.UseShellExecute = false;
                    netstatProcess.StartInfo.RedirectStandardOutput = true;
                    netstatProcess.Start();
                    var netstatOutput = netstatProcess.StandardOutput.ReadToEnd();
                    netstatProcess.WaitForExit();

                    isNgServerPortAvailable = String.IsNullOrWhiteSpace(netstatOutput);
                }
            }
            return isNgServerPortAvailable;
        }

19 Source : LocationService.cs
with GNU Lesser General Public License v3.0
from andisturber

public void LoadDevelopmentTool(DeviceModel device)
        {
            var shortVersion = string.Join(".", device.Version.Split('.').Take(2));
            PrintMessage($"为设备加载驱动版本 {shortVersion}。");

            var basePath = AppDomain.CurrentDomain.BaseDirectory + "/drivers/";

            if (!File.Exists($"{basePath}{shortVersion}/inject.dmg"))
            {
                PrintMessage($"未找到 {shortVersion} 驱动版本,请下载驱动后重新加载设备。");
                PrintMessage($"请前往:https://pan.baidu.com/s/1MPUTYJTdv7yXEtE8nMIRbQ 提取码:p9ep 按版本自行下载后放入drivers目录。");
                return;
            }
            Process.Start(new ProcessStartInfo
            {
                FileName = "injecttool",
                UseShellExecute = false,
                RedirectStandardOutput = false,
                CreateNoWindow = true,
                Arguments = ".\\drivers\\" + shortVersion + "\\inject.dmg"
            })
            .WaitForExit();
        }

19 Source : NgProxyMiddleware.cs
with MIT License
from andfomin

internal static bool IsPortAvailable(int port)
        {
            using (var process = new Process())
            {
                process.StartInfo.FileName = "cmd.exe";
                process.StartInfo.Arguments = $"/c netstat.exe -a -n -p TCP | findstr LISTENING | findstr :{port}";
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.Start();
                var netstatOutput = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                return String.IsNullOrWhiteSpace(netstatOutput);
            }
        }

19 Source : NgItemWizardWindow.xaml.cs
with MIT License
from andfomin

private void RequestNavigate(RequestNavigateEventArgs e)
        {
            var url = e.Uri.AbsoluteUri;
            Task.Factory.StartNew(() =>
            {
                using (var process = Process.Start(url))
                {
                    process.WaitForExit();
                }
            });
            e.Handled = true;
            DialogResult = false;
        }

19 Source : NgWizardHelper.cs
with MIT License
from andfomin

private static string RunCmd(string arguments, string workingDirectory, bool createNoWindow, bool redirectStandardOutput)
        {
            string output = null;
            var startInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                Arguments = arguments,
                WorkingDirectory = workingDirectory,
                UseShellExecute = false,
                CreateNoWindow = createNoWindow,
                RedirectStandardOutput = redirectStandardOutput,
            };
            using (var process = System.Diagnostics.Process.Start(startInfo))
            {
                if (redirectStandardOutput)
                {
                    output = process.StandardOutput.ReadToEnd();
                }
                process.WaitForExit();
            }
            return output;
        }

19 Source : NgProjectWizardWindow.xaml.cs
with MIT License
from andfomin

private void RequestNavigate(RequestNavigateEventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                using (var process = Process.Start(e.Uri.AbsoluteUri))
                {
                    process.WaitForExit();
                }
            });
            e.Handled = true;
            DialogResult = false;
        }

19 Source : AspNetToNgRedirector.cs
with MIT License
from andfomin

public static void Main(string[] args)
        {
            /* Visual Studio configures IIS Express to host a Kestrel server.
             * When we run the project, Visual Studio starts the IIS Express which in turn starts the Kestrel server, then launches a browser and points it to the IIS Express. 
             * We serve a page from ASP.NET Core that redirects the browser from the IIS Express to the NG Development Server.
             */

            // Visual Studio writes Byte Order Mark when saves files. 
            // Webpack fails reading such a package.json. +https://github.com/webpack/enhanced-resolve/issues/87
            // Athough the docs claim that VS is aware of the special case of package.json, 
            // apparently VS fails to recognize the file when the template wizard saves it during the project creation.
            EnsurePackageJsonFileHasNoBom();

            var webHostBuilder = new WebHostBuilder();

            string ngServeOptions = GetNgServeOptions(webHostBuilder);

            // Run "ng serve". For ASP.NET applications the working directory is the project root.
            // TODO AF20170914 replacedign explicitly ngProcess.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            var ngProcess = Process.Start("cmd.exe", "/k start ng.cmd serve"
              + (!String.IsNullOrWhiteSpace(ngServeOptions) ? " " + ngServeOptions : String.Empty)); // TODO AF20170914. Simplify: ngServeOptions??String.Empty

            var ngServerProtocol = GetNgServerProtocol(ngServeOptions);
            var ngServerPort = GetNgServerPort(ngServeOptions);
            // An NG Develpment Server may have already been started manually from the Command Prompt. Check if that is the case.
            bool isNgServerPortAvailable = IsNgServerPortAvailable(ngServerPort);

            var startPage = (isNgServerPortAvailable
              ? (StartPage
              .Replace("{{PollingUrl}}", ngServerProtocol == "https" ? PollingUrl : $"http://localhost:{ngServerPort}/")
              .Replace("{{RedirectionPageUrl}}", RedirectionPageUrl)
              .Replace("{{DebuggerWarning}}", (Debugger.IsAttached ? DebuggerWarning : String.Empty))
              )
              // Inform the developer how to specify another port.
              : PortUnavailableErrorPage
              )
              .Replace("{{StyleSection}}", StyleSection)
              ;

            var redirectionPage = RedirectionPage
              .Replace("{{NgServerProtocol}}", ngServerProtocol)
              .Replace("{{NgServerPort}}", ngServerPort.ToString());

            // We use a CancellationToken for shutting down the Kestrel server after the redirection page has been sent to the browser.
            var cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = cancellationTokenSource.Token;

            var webHost = webHostBuilder
              .UseKestrel()
              .UseIISIntegration()
              .Configure(app => app.Run(async context =>
              {
                  switch (context.Request.Path.Value)
                  {
                      case "/":
                          await context.Response.WriteAsync(startPage);
                          break;
                      case PollingUrl:
                          var isNgServerReady = await IsNgServerReady(ngServerProtocol, ngServerPort, cancellationToken);
                          context.Response.StatusCode = isNgServerReady ? StatusCodes.Status204NoContent : StatusCodes.Status503ServiceUnavailable;
                          break;
                      case RedirectionPageUrl:
                          await context.Response.WriteAsync(redirectionPage);
                          cancellationTokenSource.Cancel();
                          break;
                      default:
                          context.Response.StatusCode = StatusCodes.Status404NotFound;
                          break;
                  }

              }))
              .Build()
              ;

            // When the profile is "IIS Express" this setting is present. Sometimes we face "{{AppName}}" as the active profile, which doesn't have this setting (its value returns "production"? default?). That "{{AppName}}" profile doesn't open a web browser, so we cannot redirect anyway.
            var environmentSetting = webHostBuilder.GetSetting("environment");
            var isIISExpressEnvironment = !String.IsNullOrEmpty(environmentSetting) && (environmentSetting.ToLower() == "development");
            if (isIISExpressEnvironment)
            {
                webHost.Run(cancellationToken);
            }

            if (ngProcess != null)
            {
                ngProcess.WaitForExit();
                ngProcess.Dispose();
            }
        }

19 Source : InstantPreviewManager.cs
with Apache License 2.0
from andijakl

private static void RunAdbCommand(string fileName, string arguments, out string output, out string errors)
        {
            using (var process = new System.Diagnostics.Process())
            {
                var startInfo = new System.Diagnostics.ProcessStartInfo(fileName, arguments);
                startInfo.UseShellExecute = false;
                startInfo.RedirectStandardError = true;
                startInfo.RedirectStandardOutput = true;
                startInfo.CreateNoWindow = true;
                process.StartInfo = startInfo;

                var outputBuilder = new StringBuilder();
                var errorBuilder = new StringBuilder();
                process.OutputDataReceived += (sender, ef) => outputBuilder.Append(ef.Data);
                process.ErrorDataReceived += (sender, ef) => errorBuilder.Append(ef.Data);

                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                process.Close();

                // Trims the output strings to make comparison easier.
                output = outputBuilder.ToString().Trim();
                errors = errorBuilder.ToString().Trim();
            }
        }

19 Source : HtmlConverter.cs
with MIT License
from andrei-m-code

public byte[] FromUrl(string url, int width = 1024, ImageFormat format = ImageFormat.Jpg, int quality = 100)
        {
            var imageFormat = format.ToString().ToLower();
            var filename = Path.Combine(directory, $"{Guid.NewGuid().ToString()}.{imageFormat}");

            string args;

            if (IsLocalPath(url))
            {
                args = $"--quality {quality} --width {width} -f {imageFormat} \"{url}\" \"{filename}\"";
            }
            else
            {
                args = $"--quality {quality} --width {width} -f {imageFormat} {url} \"{filename}\"";
            }

            Process process = Process.Start(new ProcessStartInfo(toolFilepath, args)
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                CreateNoWindow = true,
                UseShellExecute = false,
                WorkingDirectory = directory,
                RedirectStandardError = true
            });

            process.ErrorDataReceived += Process_ErrorDataReceived;
            process.WaitForExit();

            if (File.Exists(filename))
            {
                var bytes = File.ReadAllBytes(filename);
                File.Delete(filename);
                return bytes;
            }

            throw new Exception("Something went wrong. Please check input parameters");
        }

19 Source : Solution.cs
with GNU General Public License v3.0
from AndreiFedarets

public bool BuildSolution(IOutput output, Configuration configuration, bool rebuild, string msbuildPath = null)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            if (!UpdateExternals(output, configuration, false, msbuildPath))
            {
                return false;
            }
            BuildResult buildResult = new BuildResult();
            Process process = new Process();
            process.StartInfo = new ProcessStartInfo(GetMsbuildPath(msbuildPath));
            string targetAction = rebuild ? "Rebuild" : "Build";
            process.StartInfo.Arguments = string.Format("{0} /t:{1} /p:Configuration={2} /m", SolutionFullName, targetAction, configuration);
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            DataReceivedEventHandler eventHandler = (s, e) => { output.WriteLine(e.Data); buildResult.ProcessMessage(e.Data); };
            try
            {
                process.OutputDataReceived += eventHandler;
                process.Start();
                process.BeginOutputReadLine();
                process.WaitForExit();
            }
            finally
            {
                process.OutputDataReceived -= eventHandler;
                buildResult.SetTime(stopwatch.Elapsed);
                BuildResult = buildResult;
            }
            return process.ExitCode == 0;
        }

19 Source : Update.cs
with MIT License
from ANF-Studios

public void DownloadWinPath(in ReleaseInfo releaseInfo, Action finalJob = null)
        {
            bool appveyor = Environment.GetEnvironmentVariable("APPVEYOR", EnvironmentVariableTarget.Process) == "True";
            if (!confirmDownload)
            {
                Console.WriteLine("Release Information:\n"
                    + $"replacedle: {releaseInfo.ReleaseName}\n"
                    + $"Version: v{releaseInfo.TagName}"
                    + (releaseInfo.IsPrerelease ? " (Prerelease)\n" : "\n")
                    + $"File: {releaseInfo.Releasereplacedet.ExecutableName}\n");
                Console.Write($"Confirm installation of WinPath v{releaseInfo.TagName} (y/n): ");

                if (!appveyor)
                    if ((Console.ReadKey()).Key == ConsoleKey.Y)
                        confirmDownload = true;
                    else
                        Environment.Exit(Environment.ExitCode);
                else
                    return;
            }

            Directory.CreateDirectory(downloadDirectory);

            Console.WriteLine("\nDownloading " + releaseInfo.Releasereplacedet.ExecutableName + "...");
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.Headers.Add(HttpRequestHeader.UserAgent, "WinPath");
                    webClient.DownloadFile(releaseInfo.Releasereplacedet.DownloadUrl, downloadDirectory + "WinPath.exe");
                    webClient.DownloadFile(releaseInfo.Updater.DownloadUrl, downloadDirectory + "WinPath.Updater.exe");
                }
            }
            catch (WebException exception)
            {
                Console.WriteLine("Couldn't download WinPath due to an error in networking:\n" + exception);
                Environment.Exit(1);
            }
            catch (Exception exception)
            {
                Console.WriteLine("Couldn't download WinPath:\n" + exception.Message);
                Environment.Exit(1);
            }
            finally
            {
                Console.WriteLine("Downloaded WinPath v" + releaseInfo.TagName + "...");
                Console.WriteLine("Installing WinPath...");

                bool administratorPermissions = IsUserAnAdmin();
                int processExitCode = 1; // Default to unsuccessful.

                ProcessStartInfo process = new ProcessStartInfo
                {
                    FileName = downloadDirectory + "WinPath.Updater.exe",
                    Arguments = "launching_from_winpath", // To tell WinPath.Updater that a user isn't launching it.
                    UseShellExecute = !administratorPermissions,
                    Verb = administratorPermissions ? string.Empty : "runas",
                    CreateNoWindow = true
                };
                try
                {
                    Console.WriteLine("Starting update...");
                    if (appveyor)
                    {
                        const string installationPath = "C:\\Program Files\\WinPath\\";
                        Directory.CreateDirectory(installationPath);
                        File.Move(downloadDirectory + "\\WinPath.exe", installationPath + "WinPath.exe");
                        processExitCode = 0;
                    }
                    else
                    {
                        var application = Process.Start(process);
                        application.WaitForExit();
                        processExitCode = application.ExitCode;
                        Console.WriteLine("Installer exited with code: " + application.ExitCode);
                    }
                }
                catch (System.ComponentModel.Win32Exception exception)
                {
                    if (exception.NativeErrorCode == 1223)
                        Console.WriteLine("Could not install WinPath because administrator permissions were not provided!");
                    else
                        Console.WriteLine("Could not install WinPath: " + exception.Message);
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Could not update WinPath: " + exception.Message);
                }
                if (processExitCode == 0) // If application exited successfully.
                {
                    WinPath.Library.UserPath userPath = WinPath.Program.GetUserPath();
                    string path = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User);
                    if (!path.EndsWith(";"))
                        Environment.SetEnvironmentVariable("Path", (path += ";"), EnvironmentVariableTarget.User);
                    path = path.Replace("/", "\\");
                    if (Environment.Is64BitOperatingSystem)
                       if (!(path.Contains("%programfiles%\\winpath", StringComparison.CurrentCultureIgnoreCase) || path.Contains("c:\\program files\\winpath", StringComparison.CurrentCultureIgnoreCase)))
                           userPath.AddToPath("%PROGRAMFILES%\\WinPath\\", true, DateTime.Now.ToFileTime().ToString());
                    else
                       if (!(path.Contains("%programfiles(x86)%\\winpath", StringComparison.CurrentCultureIgnoreCase) || path.Contains("c:\\program files (x86)\\winpath", StringComparison.CurrentCultureIgnoreCase)))
                           userPath.AddToPath("%PROGRAMFILES(X86)%\\WinPath\\", true, DateTime.Now.ToFileTime().ToString());
                    Console.WriteLine("[STATUS] Installed WinPath successfully!");
                    Environment.ExitCode = 0;
                }
                else // If not.
                {
                    Console.WriteLine("[STATUS] Could not update WinPath! Please see the log file: " + logDirectory + "log.txt");
                    Environment.ExitCode = 1;
                }
                finalJob?.Invoke();
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from Angelinsky7

static void Main(string[] args) {

            if (args.Length != 3) { Environment.Exit(3); return; }

            String msi = args[0];
            String location = args[1];
            Int32 pid = Int32.Parse(args[2]);

            if (pid == 0) { Environment.Exit(100); return; }
            if (!File.Exists(msi)) { Environment.Exit(404); return; }

            Process apptray = Process.GetProcessById(pid);
            String appNameFilename = apptray.MainModule.FileName;
            Boolean apptrayAsExited = apptray.WaitForExit(60000);

            if (!apptrayAsExited) { Environment.Exit(500); return; }

            ProcessStartInfo installerInfo = new ProcessStartInfo() {
                Arguments = $"/i {msi}",
                UseShellExecute = true,
                FileName = "msiexec",
                Verb = "runas"
            };

            Boolean installerAsExited = false;
            try {
                Process installer = Process.Start(installerInfo);
                installerAsExited = installer.WaitForExit(60000);
            } catch (Win32Exception ex) {
                if (ex.NativeErrorCode == 1223) { Environment.Exit(1223); return; }
            }

            if (installerAsExited && File.Exists(appNameFilename)) {
                Process.Start(new ProcessStartInfo() {
                    Arguments = $"/C del /Q /F {msi}",
                    CreateNoWindow = true,
                    WindowStyle = ProcessWindowStyle.Hidden,
                    FileName = "cmd",
                });
                Process.Start(appNameFilename);
            }

        }

19 Source : DnaEnvironment.cs
with MIT License
from angelsix

private static bool OpenVsCode(string path)
        {
            // Filename of command line
            var filename = string.Empty;

            // If windows...
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                // It is cmd.exe
                filename = "cmd.exe";
            // If linux...
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                // It is bin/bash
                filename = "/bin/bash";
            // If it is Mac
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                // It is bash
                filename = "bash";
            // Otherwise...
            else
                // Unknown system
                return false;

            // Check VS Code is installed
            var process = Process.Start(new ProcessStartInfo
            {
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardInput = true,
                FileName = filename,
                Arguments = "/C code --version"
            });

            // Start and wait for end
            process.WaitForExit();

            // If it did not exit...
            if (!process.HasExited)
                // Presume it isn't installed
                return false;

            // Get output
            var codeResponse = process.StandardOutput.ReadToEnd();

            // Get the output int lines
            var lines = codeResponse?.Split(new[] { "\n", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            // First line should be version string
            // If it isn't...
            if (lines == null || lines.Length <= 0 || !Version.TryParse(lines[0], out var vsVersion))
                // Presume not installed
                return false;

            // If we get here, we have got a valid response with a version number
            // so it is safe to open VS Code with the folder

            // Log it
            CoreLogger.Log($"Opening VS Code for folder '{path}'...", type: LogType.Attention);

            // Open VS Code (on new task otherwise our application doesn't exit unti this does
            var process2 = Process.Start(new ProcessStartInfo
            {
                // IMPORTANT: If you don't specify UseShellExecute = false
                //            and CreateNoWindow = true
                //            then our console will never exit until VS Code is closed
                UseShellExecute = false,
                CreateNoWindow = true,
                FileName = filename,
                Arguments = $@"/C code ""{path}""",
            });

            // Done
            return true;
        }

See More Examples