System.Diagnostics.Process.Start(System.Diagnostics.ProcessStartInfo)

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

4229 Examples 7

19 Source : NewWindows10OnScreenKeyboardController.cs
with MIT License
from AlexeiScherbakov

private static void StartTabTip()
		{
			ProcessStartInfo psi = new ProcessStartInfo(@"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe")
			{
				UseShellExecute=true
			};

			var p = Process.Start(psi);
			IntPtr handle;
			while (!NativeMethods.IsValidHandle(handle = NativeMethods.FindWindow("IPTIP_Main_Window", "")))
			{
				Thread.Sleep(100);
			}
		}

19 Source : PortForm.cs
with MIT License
from AlexGyver

private void webServerLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
      try {
        Process.Start(new ProcessStartInfo(e.Link.LinkData.ToString()));
      } catch { }
    }

19 Source : AboutBox.cs
with MIT License
from AlexGyver

private void linkLabel_LinkClicked(object sender, 
      LinkLabelLinkClickedEventArgs e) {
      try {
        Process.Start(new ProcessStartInfo(e.Link.LinkData.ToString()));
      } catch { }
    }

19 Source : ErrorWindow.xaml.cs
with MIT License
from alexleen

private void GitHubHyperLinkOnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
            e.Handled = true;
        }

19 Source : PropertyBase.cs
with MIT License
from alexleen

private static void HyperlinkOnRequestNavigate(object uri)
        {
            Process.Start(new ProcessStartInfo(uri.ToString()));
        }

19 Source : Simulation.cs
with Apache License 2.0
from Algoryx

public void OpenInNativeViewer()
    {
      if ( m_simulation == null ) {
        Debug.Log( "Unable to open simulation in native viewer.\nEditor has to be in play mode (or paused)." );
        return;
      }

      string path = Application.dataPath + @"/AGXUnityTemp/";
      if ( !System.IO.Directory.Exists( path ) )
        System.IO.Directory.CreateDirectory( path );

      var tmpFilename    = "openedInViewer.agx";
      var tmpLuaFilename = "openedInViewer.agxLua";
      var camera         = Camera.main ?? Camera.allCameras.FirstOrDefault();

      if ( camera == null ) {
        Debug.Log( "Unable to find a camera - failed to open simulation in native viewer." );
        return;
      }

      var cameraData = new
      {
        Eye               = camera.transform.position.ToHandedVec3().ToVector3(),
        Center            = ( camera.transform.position + 25.0f * camera.transform.forward ).ToHandedVec3().ToVector3(),
        Up                = camera.transform.up.ToHandedVec3().ToVector3(),
        NearClippingPlane = camera.nearClipPlane,
        FarClippingPlane  = camera.farClipPlane,
        FOV               = camera.fieldOfView
      };

      var luaFileContent = @"
replacedert( requestPlugin( ""agxOSG"" ) )
function buildScene( sim, app, root )
  replacedert( agxOSG.readFile( """ + path + tmpFilename + @""", sim, root ) )

  local cameraData             = app:getCameraData()
  cameraData.eye               = agx.Vec3( " + cameraData.Eye.x + ", " + cameraData.Eye.y + ", " + cameraData.Eye.z + @" )
  cameraData.center            = agx.Vec3( " + cameraData.Center.x + ", " + cameraData.Center.y + ", " + cameraData.Center.z + @" )
  cameraData.up                = agx.Vec3( " + cameraData.Up.x + ", " + cameraData.Up.y + ", " + cameraData.Up.z + @" )
  cameraData.nearClippingPlane = " + cameraData.NearClippingPlane + @"
  cameraData.farClippingPlane  = " + cameraData.FarClippingPlane + @"
  cameraData.fieldOfView       = " + cameraData.FOV + @"
  app:applyCameraData( cameraData )

  return root
end
if arg and not alreadyInitialized then
  alreadyInitialized = true
  local app = agxOSG.ExampleApplication()
  _G[ ""buildScene"" ] = buildScene
  app:addScene( arg[ 0 ], ""buildScene"", string.byte( ""1"" ) )
  local argParser = agxIO.ArgumentParser()
  argParser:readArguments( arg )
  if app:init( argParser ) then
    app:run()
  end
end";

      if ( !SaveToNativeFile( path + tmpFilename ) ) {
        Debug.Log( "Unable to start viewer.", this );
        return;
      }

      System.IO.File.WriteAllText( path + tmpLuaFilename, luaFileContent );

      try {
        Process.Start( new ProcessStartInfo()
        {
          FileName = @"luaagx.exe",
          Arguments = path + tmpLuaFilename + @" -p --renderDebug 1",
          UseShellExecute = false
        } );
      }
      catch ( System.Exception e ) {
        Debug.LogException( e );
      }
    }

19 Source : Utils.cs
with MIT License
from aliprogrammer69

public static void OpenExternalUrl(string url) {
            System.Diagnostics.ProcessStartInfo process = new System.Diagnostics.ProcessStartInfo(url) {
                UseShellExecute = true
            };
            System.Diagnostics.Process.Start(process);
        }

19 Source : Program.cs
with MIT License
from alkampfergit

private static void PerformTemplateExport(ConnectionManager connection)
        {
            var wordFolderManager = new WordTemplateFolderManager(options.TemplateFolder);
            var executor = new TemplateExecutor(wordFolderManager);

            //now we need to ask user parameter value
            Dictionary<string, Object> parameters = new Dictionary<string, object>();
            foreach (var commandLineParam in options.Parameters)
            {
                var splitted = commandLineParam.Split('=');
                if (splitted.Length == 2)
                {
                    Log.Debug("Found parameter {paramName} in command line with value {value}", splitted[0], splitted[1]);
                    parameters[splitted[0]] = splitted[1];
                }
                else
                {
                    Log.Error("Command line parameter {param} is not in the form name=value", commandLineParam);
                }
            }
            foreach (var parameterName in wordFolderManager.TemplateDefinition.ParameterSection.Parameters.Keys)
            {
                if (!parameters.ContainsKey(parameterName))
                {
                    Console.Write($"Parameter {parameterName}:");
                    parameters[parameterName] = Console.ReadLine();
                }
            }

            var tempFileName = Path.GetTempPath() + Guid.NewGuid().ToString();
            var generatedName = executor.GenerateFile(tempFileName, connection, options.TeamProject, parameters);
            System.Diagnostics.Process.Start(generatedName);
        }

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 : MainViewModel.cs
with MIT License
from alkampfergit

private void InnerExecuteDump()
        {
            foreach (var selectedTemplate in Templates.Where(t => t.IsSelected))
            {
                var fileName = Path.Combine(Path.GetTempPath(), selectedTemplate.TemplateName, Guid.NewGuid().ToString()) + ".txt";
                if (selectedTemplate.IsScriptTemplate)
                {
                    var executor = new TemplateExecutor(selectedTemplate.WordTemplateFolderManager);

                    //now we need to ask user parameter value
                    Dictionary<string, object> parameters = PrepareUserParameters();
                    executor.DumpWorkItem(fileName, ConnectionManager.Instance, SelectedTeamProject.Name, parameters);
                }
                else
                {
                    var selected = SelectedQuery?.Results?.Where(q => q.Selected).ToList();
                    if (selected == null || selected.Count == 0)
                    {
                        return;
                    }

                    var sb = new StringBuilder();
                    foreach (var workItemResult in selected)
                    {
                        var workItem = workItemResult.WorkItem;
                        var values = workItem.CreateDictionaryFromWorkItem();
                        foreach (var value in values)
                        {
                            sb.AppendLine($"{value.Key.PadRight(50, ' ')}={value.Value}");
                        }
                        File.WriteAllText(fileName, sb.ToString());
                    }
                }
                System.Diagnostics.Process.Start(fileName);
            }
        }

19 Source : MainViewModel.cs
with MIT License
from alkampfergit

private void ManageGeneratedWordFile(string fileName)
        {
            if (fileName.EndsWith(".docx"))
            {
                using (WordAutomationHelper helper = new WordAutomationHelper(fileName, false))
                {
                    helper.UpdateAllTocs();
                    if (GeneratePdf)
                    {
                        var pdfFile = helper.ConvertToPdf();
                        if (!String.IsNullOrEmpty(pdfFile))
                        {
                            System.Diagnostics.Process.Start(pdfFile);
                        }
                    }
                }
            }
            System.Diagnostics.Process.Start(fileName);
        }

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

private void ButtonOpenTempFolder_Click(object sender, RoutedEventArgs e)
        {
            // Opens the Temp Folder
            if (ToggleSwitchTempFolder.IsOn == false)
            {
                //Creates the temp directoy if not existent
                if (Directory.Exists(Path.Combine(Path.GetTempPath(), "NEAV1E")) == false) { Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "NEAV1E")); }
                Process.Start(Path.Combine(Path.GetTempPath(), "NEAV1E"));
            }
            else
            {
                Process.Start(TextBoxCustomTempPath.Text);
            }
        }

19 Source : SmallFunctions.cs
with MIT License
from Alkl58

public static void CheckVideoOutput()
        {
            // This checks if the video muxer created an output file
            if (File.Exists(Global.Video_Output))
            {
                FileInfo VideoOutput = new FileInfo(Global.Video_Output);
                if (VideoOutput.Length <= 50000)
                {
                    MessageBox.Show("Video Output is " + (VideoOutput.Length / 1000) + "KB.\nThere could be a muxing error.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                else
                {
                    // Deletes Temp Files only if output exists which is bigger than 50KB
                    DeleteTempFiles();
                }
            }
            else
            {
                MessageBoxResult Result = MessageBox.Show("Muxing failed. Video output not detected!\nCommon issues:\n- Video is interlaced, please enable deinterlace filter\n- Missing dependencies\n- Video stream has broken parts\n- Incorrect encoding commands\n\nOpen Log File?", "Error", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                if (Result == MessageBoxResult.Yes)
                {
                    try
                    {
                        Process.Start(Global.Video_Output + ".log");
                    }
                    catch { }
                }
            }
        }

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

public string Dump(string[] procdumpArgs)
        {
            string args = GetProcDumpArgs(procdumpArgs);

            ProcessStartInfo info = new ProcessStartInfo(ProcDumpExe, $"-accepteula {args}")
            {
                CreateNoWindow = true,
                RedirectStandardOutput = true, 
                UseShellExecute = false,
            };

            var p = Process.Start(info);
            string line;
            string dumpFileName = null;
            List<string> lines = new List<string>();
            bool procDumpError = false;
            while( (line = p.StandardOutput.ReadLine()) != null )
            {
                lines.Add(line);
                if (ShowOutput)
                {
                    Console.WriteLine(line);
                }

                if( line.Contains("Error creating dump file"))
                {
                    procDumpError = true;
                }

                if (dumpFileName == null && procDumpError == false)
                { 
                    dumpFileName = GetDumpFileName(line);
                }
            }

            if( dumpFileName == null )
            {
                if(!ShowOutput)
                {
                    lines.ForEach(Console.WriteLine);
                }
                Console.WriteLine($"Error: Could not create dump file with procdump args: {args}!");
                return null;
            }
            else
            {
                Console.WriteLine($"Dump file {dumpFileName} created.");
            }


            int pid = FindPidInProcDumpArgs(procdumpArgs, out string exeName);

            if(pid == 0)
            {
                ProcessFilter filter = new ProcessFilter(exeName ?? "");
                pid = filter.GetMatchingPids().FirstOrDefault();
            }

            if (pid != 0)
            {
                string outFile = TargetInformation.GetreplacedociatedVMMapFile(dumpFileName);
                VMMap.SaveVMmapDataToFile(pid, outFile);
            }
            else
            {
                Console.WriteLine($"Error: Could not create find process id of dumped process {exeName}. No VMMap information is saved. ");
            }

            if (VerifyDump && !CanLoadDump(dumpFileName))
            {
                Console.WriteLine($"Error: Dump file cannot be parsed with Memreplacedyzer. Managed Heap might be in an inconsistent state.");
                dumpFileName = null;
            }


            return dumpFileName;
        }

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 : 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 : 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 : DumpCreatorTests.cs
with GNU Lesser General Public License v3.0
from Alois-xx

internal static Process AllocStrings(string exe= StringAllocExe, int n=0)
        {
            ProcessStartInfo info = new ProcessStartInfo(exe, $"{n}")
            {
                CreateNoWindow= true,
                UseShellExecute = false,
                RedirectStandardOutput = true
            };

            var p = Process.Start(info);
            string line = null;
            while( (line = p.StandardOutput.ReadLine()) != null)
            {
                if( line.Contains("All strings allocated"))
                {
                    break;
                }
            }

            return p;
        }

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 : ModDownloader.cs
with GNU General Public License v3.0
from amakvana

public async Task DownloadreplacedleModsAsync(string replacedleName, string replacedleId, string modWebsiteUrl, bool deleteExistingMods)
        {
            // fetch all download links for current game
            // extract them into appropriate directory

            var web = new HtmlWeb();
            var htmlDoc = web.Load(modWebsiteUrl);
            var nodes = htmlDoc.DoreplacedentNode.SelectNodes(@"//h3[contains(., """ + replacedleName + "\")]/following::table[1]//td//a");

            // if true, delete existing mods 
            if (deleteExistingMods)
            {
                DeleteModData($@"{UserDirPath}\load\{replacedleId}");
            }

            // download all mods for game 
            if (nodes != null)
            {
                using (var wc = new WebClient())
                {
                    foreach (HtmlNode node in nodes)
                    {
                        string modName = node.InnerText;
                        string modDownloadUrl = node.Attributes["href"].Value.Trim();
                        string fileName = modDownloadUrl.Split('/').Last().Trim();

                        // if url is gamebanana, scrape page and get actual download
                        //if (modDownloadUrl.Contains("gamebanana.com"))
                        //{
                        //    // modUrl = GetGameBananaDownloadUrl(modUrl, out fileName);

                        //    // NEED to fix when files are extracted from GameBanana packages
                        //}
                        //else if (modDownloadUrl.Contains("bit.ly"))
                        //{
                        //    // coming soon ...
                        //}
                        if (modDownloadUrl.EndsWith(".zip") || modDownloadUrl.EndsWith(".rar") || modDownloadUrl.EndsWith(".7z"))
                        {
                            wc.DownloadFileCompleted += (s, e) =>
                            {
                                UpdateProgress(0, $"Unpacking {fileName} ...");

                                // unzip downloaded mod 
                                var psi = new ProcessStartInfo
                                {
                                    WindowStyle = ProcessWindowStyle.Hidden,
                                    FileName = $@"{UserDirPath}\7z\7z.exe",
                                    Arguments = "x \"" + $@"{UserDirPath}\load\{replacedleId}\{fileName}" + "\" -o" + $@"{UserDirPath}\load\{replacedleId}" + " -aoa"
                                };
                                using (var p = Process.Start(psi))
                                {
                                    UpdateProgress(100, "Done");
                                }
                            };
                            wc.DownloadProgressChanged += (s, e) => UpdateProgress(e.ProgressPercentage, $"Downloading {fileName} ...");
                            await wc.DownloadFileTaskAsync(modDownloadUrl, $"{UserDirPath}/load/{replacedleId}/{fileName}");
                        }
                    }
                }
            }
        }

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 : TUNTAPController.cs
with MIT License
from AmazingDM

private void SetupRouteTable(Mode mode)
        {
            Global.MainForm.StatusText(i18N.Translate("SetupBypreplaced"));
            Logging.Info("设置路由规则");

            #region Rule IPs

            switch (mode.Type)
            {
                case 1:
                    // 代理规则
                    Logging.Info("代理 → 规则 IP");
                    RouteAction(Action.Create, mode.FullRule, RouteType.TUNTAP);

                    //处理 NAT 类型检测,由于协议的原因,无法仅通过域名确定需要代理的 IP,自己记录解析了返回的 IP,仅支持默认检测服务器
                    if (Global.Settings.STUN_Server == "stun.stunprotocol.org")
                        try
                        {
                            Logging.Info("代理 → STUN 服务器 IP");
                            RouteAction(Action.Create,
                                new[]
                                {
                                    Dns.GetHostAddresses(Global.Settings.STUN_Server)[0],
                                    Dns.GetHostAddresses("stunresponse.coldthunder11.com")[0]
                                }.Select(ip => $"{ip}/32"),
                                RouteType.TUNTAP);
                        }
                        catch
                        {
                            Logging.Info("NAT 类型测试域名解析失败,将不会被添加到代理列表");
                        }

                    if (Global.Settings.TUNTAP.ProxyDNS)
                    {
                        Logging.Info("代理 → 自定义 DNS");
                        if (Global.Settings.TUNTAP.UseCustomDNS)
                            RouteAction(Action.Create,
                                Global.Settings.TUNTAP.DNS.Select(ip => $"{ip}/32"),
                                RouteType.TUNTAP);
                        else
                            RouteAction(Action.Create,
                                new[] {"1.1.1.1", "8.8.8.8", "9.9.9.9", "185.222.222.222"}.Select(ip => $"{ip}/32"),
                                RouteType.TUNTAP);
                    }

                    break;
                case 2:
                    // 绕过规则

                    // 将 TUN/TAP 网卡权重放到最高
                    Process.Start(new ProcessStartInfo
                        {
                            FileName = "netsh",
                            Arguments = $"interface ip set interface {Global.TUNTAP.Index} metric=0",
                            WindowStyle = ProcessWindowStyle.Hidden,
                            UseShellExecute = true,
                            CreateNoWindow = true
                        }
                    );

                    Logging.Info("绕行 → 规则 IP");
                    RouteAction(Action.Create, mode.FullRule, RouteType.Outbound);
                    break;
            }

            #endregion

            Logging.Info("绕行 → 服务器 IP");
            if (!IPAddress.IsLoopback(_serverAddresses))
                RouteAction(Action.Create, $"{_serverAddresses}/32", RouteType.Outbound);

            Logging.Info("绕行 → 全局绕过 IP");
            RouteAction(Action.Create, Global.Settings.BypreplacedIPs, RouteType.Outbound);

            if (mode.Type == 2)
            {
                // 绕过规则
                Logging.Info("代理 → 全局");
                RouteAction(Action.Create, "0.0.0.0/0", RouteType.TUNTAP);
            }
        }

19 Source : Utils.cs
with MIT License
from AmazingDM

public static bool Open(string path)
        {
            try
            {
                Process.Start(new ProcessStartInfo
                {
                    FileName = "explorer.exe",
                    Arguments = path,
                    UseShellExecute = true
                });
                return true;
            }
            catch
            {
                return false;
            }
        }

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 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 : LauncherUpdater.cs
with GNU General Public License v3.0
from AM2R-Community-Developers

public static void Main()
        {
            log.Info("Running update check...");

            string version = VERSION.Replace(".", "");

            //update section

            //delete old files that have been left
            if (File.Exists(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak"))
            {
                log.Info("AM2RLauncher.bak detected. Removing file.");
                File.Delete(CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak");
            }
            if (currentPlatform.IsWinForms && File.Exists(oldConfigPath))
            {
                log.Info(CrossPlatformOperations.LAUNCHERNAME + ".oldCfg detected. Removing file.");
                File.Delete(oldConfigPath);
            }
            if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/oldLib"))
            {
                log.Info("Old lib folder detected, removing folder.");
                Directory.Delete(CrossPlatformOperations.CURRENTPATH + "/oldLib", true);
            }

            // Clean up old update libs
            if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib"))
            {
                foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles())
                {
                    if (file.Name.EndsWith(".bak"))
                        file.Delete();
                }

                // Do the same for each subdir
                foreach (DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories())
                {
                    foreach (FileInfo file in dir.GetFiles())
                    {
                        if (file.Name.EndsWith(".bak"))
                            file.Delete();
                    }
                }
            }

            //check settings if autoUpdateLauncher is set to true
            bool autoUpdate = bool.Parse(CrossPlatformOperations.ReadFromConfig("AutoUpdateLauncher"));

            if (autoUpdate)
            {
                log.Info("AutoUpdate Launcher set to true!");

                //this is supposed to fix the updater throwing an exception on windows 7 and earlier(?)
                //see this for information: https://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel and https://stackoverflow.com/a/50977774
                if (currentPlatform.IsWinForms)
                {
                    ServicePointManager.Expect100Continue = true;
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                }

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest");
                HttpWebResponse response = null;
                try
                {        
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException)
                {
                    log.Error("WebException caught! Displaying MessageBox.");
                    MessageBox.Show(Language.Text.NoInternetConnection);
                    return;
                }

                Uri realUri = response.ResponseUri;
                string onlineVersion = realUri.AbsoluteUri.Substring(realUri.AbsoluteUri.LastIndexOf('/') + 1);
                bool isCurrentVersionOutdated = false;

                string[] localVersionArray = VERSION.Split('.');
                string[] onlineVersionArray = onlineVersion.Split('.');

                for (int i = 0; i < localVersionArray.Length; i++)
                {
                    if (int.Parse(onlineVersionArray[i]) > int.Parse(localVersionArray[i]))
                    {
                        isCurrentVersionOutdated = true;
                        break;
                    }
                }

                if (isCurrentVersionOutdated)
                {
                    log.Info("Current version (" + VERSION + ") is outdated! Initiating update for version " + onlineVersion + ".");

                    string tmpUpdatePath = CrossPlatformOperations.CURRENTPATH + "/tmpupdate/";
                    string zipPath = CrossPlatformOperations.CURRENTPATH + "/launcher.zip";

                    // Clean tmpupdate
                    if (Directory.Exists(tmpUpdatePath))
                        Directory.Delete(tmpUpdatePath);
                    if (!Directory.Exists(tmpUpdatePath))
                        Directory.CreateDirectory(tmpUpdatePath);

                    try
                    { 
                        using (var client = new WebClient())
                        {
                            string platformSuffix = "";
                            if (currentPlatform.IsWinForms) platformSuffix = "_win";
                            else if (currentPlatform.IsGtk) platformSuffix = "_lin";

                            log.Info("Downloading https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip to " + zipPath + ".");
                            
                            client.DownloadFile("https://github.com/AM2R-Community-Developers/AM2RLauncher/releases/latest/download/AM2RLauncher_" + onlineVersion + platformSuffix + ".zip", zipPath);

                            log.Info("File successfully downloaded.");
                        }
                    }
                    catch(UnauthorizedAccessException)
                    {
                        log.Error("UnauthorizedAccessException caught! Displaying MessageBox.");
                        MessageBox.Show(Language.Text.UnauthorizedAccessMessage);
                        return;
                    }

                    ZipFile.ExtractToDirectory(zipPath, tmpUpdatePath);
                    log.Info("Updates successfully extracted to " + tmpUpdatePath);

                    File.Delete(zipPath);
                    File.Move(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME, CrossPlatformOperations.CURRENTPATH + "/AM2RLauncher.bak");
                    if (currentPlatform.IsWinForms) File.Move(CrossPlatformOperations.LAUNCHERNAME + ".config", CrossPlatformOperations.LAUNCHERNAME + ".oldCfg");

                    foreach (var file in new DirectoryInfo(tmpUpdatePath).GetFiles())
                    {
                        log.Info("Moving " +  file.FullName + " to " + CrossPlatformOperations.CURRENTPATH + "/" + file.Name);
                        File.Copy(file.FullName, updatePath + "/" + file.Name, true);
                    }
                    // for windows, the actual application is in "AM2RLauncher.dll". Which means, we need to update the lib folder as well.
                    if (currentPlatform.IsWinForms && Directory.Exists(CrossPlatformOperations.CURRENTPATH + "/lib"))
                    {
                        // Directory.Move(CrossPlatformOperations.CURRENTPATH + "/lib", CrossPlatformOperations.CURRENTPATH + "/oldLib");
                        // So, because Windows behavior is dumb...

                        // Rename all files in lib to *.bak
                        foreach (FileInfo file in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetFiles())
                        {
                            file.CopyTo(file.Directory + file.Name + ".bak");
                        }

                        // Do the same for each subdir
                        foreach(DirectoryInfo dir in new DirectoryInfo(CrossPlatformOperations.CURRENTPATH + "/lib").GetDirectories())
                        {
                            foreach (FileInfo file in dir.GetFiles())
                            {
                                file.CopyTo(file.Directory + file.Name + ".bak");
                            }
                        }

                        // Yes, the above calls could be recursive. No, I can't be bothered to make them as such.

                        HelperMethods.DirectoryCopy(tmpUpdatePath + "lib", CrossPlatformOperations.CURRENTPATH + "/lib", true);
                    }
                    
                    Directory.Delete(tmpUpdatePath, true);

                    CrossPlatformOperations.CopyOldConfigToNewConfig();

                    log.Info("Files extracted. Preparing to restart executable...");

                    if (currentPlatform.IsGtk) System.Diagnostics.Process.Start("chmod", "+x ./AM2RLauncher.Gtk");

                    System.Diagnostics.Process.Start(updatePath + "/" + CrossPlatformOperations.LAUNCHERNAME);
                    Environment.Exit(0);
                }
            }
            else
            {
                log.Info("AutoUpdate Launcher set to false. Exiting update check.");
            }
        }

19 Source : UpdateChecker.cs
with MIT License
from AmazingDM

public static async Task UpdateNetch(DownloadProgressChangedEventHandler onDownloadProgressChanged)
        {
            using WebClient client = new();

            var latestVersionDownloadUrl = LatestRelease.replacedets[0].browser_download_url;
            var tagPage = await client.DownloadStringTaskAsync(LatestVersionUrl);
            var match = Regex.Match(tagPage, @"<td .*>(?<sha256>.*)</td>", RegexOptions.Singleline);

            // TODO Replace with regex get basename and sha256 
            var fileName = Path.GetFileName(new Uri(latestVersionDownloadUrl).LocalPath);
            fileName = fileName.Insert(fileName.LastIndexOf('.'), LatestVersionNumber);
            var fileFullPath = Path.Combine(Global.NetchDir, "data", fileName);

            var sha256 = match.Groups["sha256"].Value;

            if (File.Exists(fileFullPath))
            {
                if (Utils.Utils.SHA256CheckSum(fileFullPath) == sha256)
                {
                    RunUpdater();
                    return;
                }

                File.Delete(fileFullPath);
            }

            try
            {
                client.DownloadProgressChanged += onDownloadProgressChanged;
                await client.DownloadFileTaskAsync(new Uri(latestVersionDownloadUrl), fileFullPath);
                client.DownloadProgressChanged -= onDownloadProgressChanged;
            }
            catch (Exception e)
            {
                throw new Exception(i18N.Translate("Download Update Failed", ": ") + e.Message);
            }

            if (Utils.Utils.SHA256CheckSum(fileFullPath) != sha256)
                throw new Exception(i18N.Translate("The downloaded file has the wrong hash"));

            RunUpdater();

            void RunUpdater()
            {
                // if debugging process stopped, debugger will kill child processes!!!!
                // 调试进程结束,调试器将会杀死子进程
                // uncomment if(!Debugger.isAttach) block in NetchUpdater Project's main() method and attach to NetchUpdater process to debug
                // 在 NetchUpdater 项目的  main() 方法中取消注释 if(!Debugger.isAttach)块,并附加到 NetchUpdater 进程进行调试
                Process.Start(new ProcessStartInfo
                {
                    FileName = Path.Combine(Global.NetchDir, "NetchUpdater.exe"),
                    Arguments =
                        $"{Global.Settings.UDPSocketPort} \"{fileFullPath}\" \"{Global.NetchDir}\""
                });
            }
        }

19 Source : AboutPage.xaml.cs
with GNU General Public License v3.0
from Amebis

protected void Website_Click(object sender, RoutedEventArgs e)
        {
            Process.Start(eduVPN.Properties.Settings.Default.ClientAboutUri.AbsoluteUri);
        }

19 Source : AuthorizationPage.cs
with GNU General Public License v3.0
from Amebis

public void OnRequestAuthorization(object sender, RequestAuthorizationEventArgs e)
        {
            if (!(sender is Server authenticatingServer))
                return;

            e.TokenOrigin = RequestAuthorizationEventArgs.TokenOriginType.None;
            e.AccessToken = null;

            lock (Properties.Settings.Default.AccessTokenCache)
            {
                if (e.SourcePolicy != RequestAuthorizationEventArgs.SourcePolicyType.ForceAuthorization)
                {
                    var key = authenticatingServer.Base.AbsoluteUri;
                    if (Properties.Settings.Default.AccessTokenCache.TryGetValue(key, out var accessToken))
                    {
                        if (!e.ForceRefresh && DateTime.Now < accessToken.Expires)
                        {
                            e.TokenOrigin = RequestAuthorizationEventArgs.TokenOriginType.Saved;
                            e.AccessToken = accessToken;
                            return;
                        }

                        // Token refresh was explicitly requested or the token expired. Refresh it.
                        if (accessToken is InvalidToken)
                        {
                            // Invalid token is not refreshable.
                            Properties.Settings.Default.AccessTokenCache.Remove(key);
                        }
                        else
                        {
                            // Get API endpoints. (Not called from the UI thread or already cached by now. Otherwise it would need to be spawned as a background task to avoid deadlock.)
                            var api = authenticatingServer.GetEndpoints(Window.Abort.Token);

                            // Prepare web request.
                            var request = WebRequest.Create(api.TokenEndpoint);
                            request.CachePolicy = Xml.Response.CachePolicy;
                            request.Proxy = null;
                            if (request is HttpWebRequest requestHTTP)
                                requestHTTP.UserAgent = Xml.Response.UserAgent;

                            try
                            {
                                accessToken = accessToken.RefreshToken(request, null, Window.Abort.Token);

                                // Update access token cache.
                                Properties.Settings.Default.AccessTokenCache[key] = accessToken;

                                // If we got here, return the token.
                                e.TokenOrigin = RequestAuthorizationEventArgs.TokenOriginType.Refreshed;
                                e.AccessToken = accessToken;
                                return;
                            }
                            catch (AccessTokenException ex)
                            {
                                if (ex.ErrorCode == AccessTokenException.ErrorCodeType.InvalidGrant)
                                {
                                    // The grant has been revoked. Drop the access token.
                                    Properties.Settings.Default.AccessTokenCache.Remove(key);
                                }
                                else
                                    throw;
                            }
                        }
                    }
                }

                if (e.SourcePolicy != RequestAuthorizationEventArgs.SourcePolicyType.SavedOnly)
                {
                    // We're in the background thread - notify via dispatcher.
                    Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
                    {
                        Wizard.TaskCount++;
                        ReturnPage = Wizard.CurrentPage;
                        Wizard.CurrentPage = this;
                        AuthorizationInProgress = new CancellationTokenSource();
                    }));
                    try
                    {
                        // Get API endpoints. (Not called from the UI thread. Otherwise it would need to be spawned as a background task to avoid deadlock.)
                        var api = authenticatingServer.GetEndpoints(Window.Abort.Token);

                        // Prepare new authorization grant.
                        AuthorizationGrant authorizationGrant = null;
                        Uri callbackUri = null;
                        var httpListener = new eduOAuth.HttpListener(IPAddress.Loopback, 0);
                        httpListener.HttpCallback += (object _, HttpCallbackEventArgs eHTTPCallback) =>
                        {
                            Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
                            {
                                callbackUri = eHTTPCallback.Uri;
                                AuthorizationInProgress.Cancel();
                                Wizard.CurrentPage = ReturnPage;
                            }));
                        };
                        httpListener.HttpRequest += (object _, HttpRequestEventArgs eHTTPRequest) =>
                        {
                            if (eHTTPRequest.Uri.AbsolutePath.ToLowerInvariant() == "/favicon.ico")
                            {
                                var res = System.Windows.Application.GetResourceStream(new Uri("pack://application:,,,/Resources/App.ico"));
                                eHTTPRequest.Type = res.ContentType;
                                eHTTPRequest.Content = res.Stream;
                            }
                        };
                        httpListener.Start();
                        try
                        {
                            // Make the authorization URI.
                            authorizationGrant = new AuthorizationGrant(
                                api.AuthorizationEndpoint,
                                new Uri(string.Format("http://{0}:{1}/callback", ((IPEndPoint)httpListener.LocalEndpoint).Address, ((IPEndPoint)httpListener.LocalEndpoint).Port)),
                                Properties.Settings.Default.ClientId + ".windows",
                                new HashSet<string>() { e.Scope },
                                AuthorizationGrant.CodeChallengeAlgorithmType.S256);
                            var authorizationUri = authorizationGrant.AuthorizationUri;
                            if (authenticatingServer is SecureInternetServer srv &&
                                srv.AuthenticationUriTemplate != null)
                            {
                                // Envelope authorization URI and organization identifier.
                                authorizationUri = new Uri(srv.AuthenticationUriTemplate
                                    .Replace("@RETURN_TO@", HttpUtility.UrlEncode(authorizationUri.ToString()))
                                    .Replace("@ORG_ID@", HttpUtility.UrlEncode(srv.OrganizationId)));
                            }

                            // Trigger authorization.
                            Process.Start(authorizationUri.ToString());

                            // Wait for a change: either callback is invoked, either user cancels.
                            CancellationTokenSource.CreateLinkedTokenSource(AuthorizationInProgress.Token, Window.Abort.Token).Token.WaitHandle.WaitOne();
                        }
                        finally
                        {
                            // Delay HTTP server shutdown allowing browser to finish loading content.
                            new Thread(new ThreadStart(() =>
                            {
                                Window.Abort.Token.WaitHandle.WaitOne(5 * 1000);
                                httpListener.Stop();
                            })).Start();
                        }

                        if (callbackUri == null)
                            throw new OperationCanceledException();

                        // Get access token from authorization grant.
                        var request = WebRequest.Create(api.TokenEndpoint);
                        request.CachePolicy = Xml.Response.CachePolicy;
                        request.Proxy = null;
                        if (request is HttpWebRequest requestHTTP)
                            requestHTTP.UserAgent = Xml.Response.UserAgent;
                        e.AccessToken = authorizationGrant.ProcessResponse(
                            HttpUtility.ParseQueryString(callbackUri.Query),
                            request,
                            null,
                            Window.Abort.Token);
                        Window.Abort.Token.ThrowIfCancellationRequested();

                        // Save access token to the cache.
                        e.TokenOrigin = RequestAuthorizationEventArgs.TokenOriginType.Authorized;
                        Properties.Settings.Default.AccessTokenCache[authenticatingServer.Base.AbsoluteUri] = e.AccessToken;
                    }
                    finally { Wizard.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => Wizard.TaskCount--)); }
                }
            }
        }

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

public static void OpenFile(string filePath)
        {
            Process.Start(new ProcessStartInfo
            {
                FileName = filePath,
                UseShellExecute = true,
                Verb = "open"
            });
        }

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

public static void OpenDirectory(string directoryPath)
        {
            Process.Start(new ProcessStartInfo
            {
                FileName = directoryPath,
                UseShellExecute = true,
                Verb = "open"
            });
        }

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

public override void OnExecute(CommandEventArgs e)
        {
            AnkhMessageBox mb = new AnkhMessageBox(e.Context);

            // Cache items to avoid problems when selection changes by opening editor
            List<SvnItem> items = new List<SvnItem>(e.Selection.GetSelectedSvnItems(false));

            foreach (SvnItem item in items)
            {
                if (!item.Exists)
                    continue;

                bool selectInSolutionExplorer = false;

                try
                {
                    switch (e.Command)
                    {
                        case AnkhCommand.ItemOpenVisualStudio:
                            IProjectFileMapper mapper = e.GetService<IProjectFileMapper>();

                            if (mapper.IsProjectFileOrSolution(item.FullPath))
                            {
                                selectInSolutionExplorer = true;
                                break;
                            }
                            if (item.IsDirectory)
                                goto case AnkhCommand.ItemOpenWindows;

                            VsShellUtilities.OpenDoreplacedent(e.Context, item.FullPath);
                            break;
                        case AnkhCommand.ItemOpenTextEditor:
                            {
                                IVsUIHierarchy hier;
                                IVsWindowFrame frame;
                                uint id;

                                if (!item.IsFile)
                                    continue;

                                VsShellUtilities.OpenDoreplacedent(e.Context, item.FullPath, VSConstants.LOGVIEWID_TextView, out hier, out id, out frame);
                            }
                            break;
                        case AnkhCommand.ItemOpenWindows:
                            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(item.FullPath);
                            psi.Verb = "open";
                            System.Diagnostics.Process.Start(psi);
                            break;
                    }
                }
                catch (IOException ee)
                {
                    mb.Show(ee.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (COMException ee)
                {
                    mb.Show(ee.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (InvalidOperationException ee)
                {
                    mb.Show(ee.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (System.ComponentModel.Win32Exception ee)
                {
                    mb.Show(ee.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                if (selectInSolutionExplorer)
                {
                    IVsUIHierarchyWindow hierWindow = VsShellUtilities.GetUIHierarchyWindow(e.Context, new Guid(ToolWindowGuids80.SolutionExplorer));

                    IVsProject project = VsShellUtilities.GetProject(e.Context, item.FullPath) as IVsProject;

                    if (hierWindow != null)
                    {
                        int found;
                        uint id;
                        VSDOreplacedENTPRIORITY[] prio = new VSDOreplacedENTPRIORITY[1];
                        if (project != null && VSErr.Succeeded(project.IsDoreplacedentInProject(item.FullPath, out found, prio, out id)) && found != 0)
                        {
                            hierWindow.ExpandItem(project as IVsUIHierarchy, id, EXPANDFLAGS.EXPF_Selecreplacedem);
                        }
                        else if (string.Equals(item.FullPath, e.Selection.SolutionFilename, StringComparison.OrdinalIgnoreCase))
                            hierWindow.ExpandItem(e.GetService<IVsUIHierarchy>(typeof(SVsSolution)), VSItemId.Root, EXPANDFLAGS.EXPF_Selecreplacedem);

                        // Now try to activate the solution explorer
                        IVsWindowFrame solutionExplorer;
                        Guid solutionExplorerGuid = new Guid(ToolWindowGuids80.SolutionExplorer);
                        IVsUIShell shell = e.GetService<IVsUIShell>(typeof(SVsUIShell));

                        if (shell != null)
                        {
                            shell.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fForceCreate, ref solutionExplorerGuid, out solutionExplorer);

                            if (solutionExplorer != null)
                                solutionExplorer.Show();
                        }
                    }
                }
            }
        }

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

public static void ShellExecute(IWin32Window Owner, string strFileName, string strVerb)
        {
            ProcessStartInfo SI = new ProcessStartInfo();

            SI.ErrorDialog = true;
            if (Owner != null)
            {
                SI.ErrorDialogParentHandle = Owner.Handle;
            }
            SI.FileName = strFileName;
            SI.UseShellExecute = true;
            SI.Verb = strVerb;

            try
            {
                Process.Start(SI);
            }
            catch(Exception e)
            {
                // Kills VS if it fails
                MessageBox.Show(e.ToString());
            } 
        }

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

private void OnOpenFolder(object sender, CommandEventArgs e)
        {
            foreach (SvnItem item in e.Selection.GetSelectedSvnItems(false))
            {
                if (item.Exists)
                    System.Diagnostics.Process.Start(item.IsDirectory ? item.FullPath : SvnTools.GetNormalizedDirectoryName(item.FullPath));
            }
        }

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

private void NavigateInExternalBrowser(Uri url)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = url.AbsoluteUri;
            startInfo.UseShellExecute = true;
            startInfo.Verb = "Open";
            Process.Start(startInfo);
        }

19 Source : AboutForm.cs
with Mozilla Public License 2.0
from amrali-eg

private void OnLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string url = (string)e.Link.LinkData;
            ProcessStartInfo startInfo = new ProcessStartInfo(url) {UseShellExecute = true};
            Process.Start(startInfo);
        }

19 Source : MainForm.cs
with Mozilla Public License 2.0
from amrali-eg

private void OnHelp(object sender, EventArgs e)
        {
            ProcessStartInfo psi =
                new ProcessStartInfo("http://encodingchecker.codeplex.com/doreplacedentation") { UseShellExecute = true };
            Process.Start(psi);
        }

19 Source : ClientServerLog.cs
with MIT License
from Analogy-LogViewer

private void bBtnOpenFolder_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (lBoxFiles.SelectedItem != null)
            {
                var filename = (lBoxFiles.SelectedItem as FileInfo)?.FullName;
                if (filename == null || !File.Exists(filename))
                {
                    return;
                }

                try
                {
                    Process.Start("explorer.exe", "/select, \"" + filename + "\"");
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message, @"Error Opening file location", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
        }

19 Source : MainWindow.xaml.cs
with MIT License
from AmRo045

private void Hyperlink_OnRequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
            e.Handled = true;
        }

19 Source : HyperlinkButton.cs
with MIT License
from amwx

protected override void OnClick()
		{
			base.OnClick();

			if (NavigateUri != null)
			{
				try
				{
					// NOTE: Will not open avares files or anything embedded in the replacedembly
					Process.Start(new ProcessStartInfo(NavigateUri.ToString()) { UseShellExecute = true, Verb = "open" });
				}
				catch
				{
					Logger.TryGet(LogEventLevel.Error, $"Unable to open Uri {NavigateUri}");
				}
			}
		}

19 Source : UpdateManager.cs
with MIT License
from Analogy-LogViewer

public async Task InitiateUpdate(string replacedle, string downloadURL, bool forceOverride)
        {
            if (string.IsNullOrEmpty(replacedle) || string.IsNullOrEmpty(downloadURL))
            {
                return;
            }

            if (XtraMessageBox.Show(
                    "Updating the application will close the current instance." + Environment.NewLine +
                    "Do you want to update right Now?", @"Update Confirmation", MessageBoxButtons.YesNo) ==
                DialogResult.Yes)
            {
                await DownloadUpdaterIfNeeded();
                if (File.Exists(UpdaterExecutable))
                {
                    var processStartInfo = new ProcessStartInfo();
                    //string data = $"\"replacedle={replacedle}\" DownloadURL:{downloadURL} \"TargetFolder:{Utils.CurrentDirectory()}\" OverrideFiles={forceOverride}";
                    string data = $"\"{replacedle}\" {downloadURL} \"{Utils.CurrentDirectory()}\" {forceOverride}";
                    processStartInfo.Arguments = data;
                    processStartInfo.Verb = "runas";
                    processStartInfo.FileName = UpdaterExecutable;
                    try
                    {
                        Process.Start(processStartInfo);
                        Application.Exit();
                    }
                    catch (Exception ex)
                    {
                        XtraMessageBox.Show($"Error during Updater: {ex.Message}", @"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    XtraMessageBox.Show(
                        "Updater was not found. Please submit this issue with the following information" +
                        Environment.NewLine +
                        $"Current Directory: {Environment.CurrentDirectory}", @"Error", MessageBoxButtons.OK,
                        MessageBoxIcon.Error);

                }
            }
        }

19 Source : FileSystemUC.cs
with MIT License
from Analogy-LogViewer

private void bBtnOpen_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (lBoxFiles.SelectedItem != null)
            {
                var filename = (lBoxFiles.SelectedItem as FileInfo)?.FullName;
                if (filename == null || !File.Exists(filename))
                {
                    return;
                }

                Process.Start("explorer.exe", "/select, \"" + filename + "\"");
            }
        }

19 Source : Utils.cs
with MIT License
from Analogy-LogViewer

public static void OpenLink(string url)
        {
            try
            {
                Process.Start(new ProcessStartInfo(url)
                {
                    UseShellExecute = true,
                    Verb = "open"
                });
            }
            catch (Exception exception)
            {
                replacedogyLogger.Instance.LogException($"Error: {exception.Message}", exception, "");
            }
        }

19 Source : BuildDeployWindow.cs
with MIT License
from anderm

private void OnGUI()
        {
            GUILayout.Space(GUISectionOffset);

            // Setup
            int buttonWidth_Quarter = Screen.width / 4;
            int buttonWidth_Half = Screen.width / 2;
            int buttonWidth_Full = Screen.width - 25;
            var locatorHasData = XdeGuestLocator.HasData;
            var locatorIsSearching = XdeGuestLocator.IsSearching;
            var xdeGuestIpAddress = XdeGuestLocator.GuestIpAddress;

            // Quick Options
            GUILayout.BeginVertical();
            GUILayout.Label("Quick Options");

            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            // Build & Run button...
            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();
                GUI.enabled = ShouldBuildSLNBeEnabled;

                if (GUILayout.Button((!locatorIsSearching && locatorHasData || HoloLensUsbConnected)
                    ? "Build SLN, Build APPX, then Install"
                    : "Build SLN, Build APPX",
                    GUILayout.Width(buttonWidth_Half - 20)))
                {
                    // Build SLN
                    EditorApplication.delayCall += () => { BuildAll(!locatorIsSearching && locatorHasData || HoloLensUsbConnected); };
                }

                GUI.enabled = true;

                if (GUILayout.Button("Open Player Settings", GUILayout.Width(buttonWidth_Quarter)))
                {
                    EditorApplication.ExecuteMenuItem("Edit/Project Settings/Player");
                }

                if (GUILayout.Button(string.IsNullOrEmpty(wsaCertPath) ? "Select Certificate" : wsaCertPath, GUILayout.Width(buttonWidth_Quarter)))
                {
                    string path = EditorUtility.OpenFilePanel("Select Certificate", Application.dataPath, "pfx");
                    wsaCertPath = path.Substring(path.LastIndexOf("/", StringComparison.Ordinal) + 1);

                    if (!string.IsNullOrEmpty(path))
                    {
                        CertificatePreplacedwordWindow.Show(path);
                    }
                    else
                    {
                        PlayerSettings.WSA.SetCertificate(string.Empty, string.Empty);
                    }
                }
            }

            GUILayout.EndVertical();

            // Build section
            GUILayout.BeginVertical();
            GUILayout.Label("SLN");

            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            // Build directory (and save setting, if it's changed)
            string curBuildDirectory = BuildDeployPrefs.BuildDirectory;
            string newBuildDirectory = EditorGUILayout.TextField(GUIHorizSpacer + "Build directory", curBuildDirectory);

            if (newBuildDirectory != curBuildDirectory)
            {
                BuildDeployPrefs.BuildDirectory = newBuildDirectory;
                curBuildDirectory = newBuildDirectory;
            }

            // Build SLN button
            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();

                float previousLabelWidth = EditorGUIUtility.labelWidth;

                // Generate C# Project References
                EditorGUIUtility.labelWidth = 105;
                bool generateReferenceProjects = EditorUserBuildSettings.wsaGenerateReferenceProjects;
                bool shouldGenerateProjects = EditorGUILayout.Toggle("Unity C# Projects", generateReferenceProjects);

                if (shouldGenerateProjects != generateReferenceProjects)
                {
                    EditorUserBuildSettings.wsaGenerateReferenceProjects = shouldGenerateProjects;
                }

                // Restore previous label width
                EditorGUIUtility.labelWidth = previousLabelWidth;

                GUI.enabled = ShouldOpenSLNBeEnabled;

                if (GUILayout.Button("Open SLN", GUILayout.Width(buttonWidth_Quarter)))
                {
                    // Open SLN
                    string slnFilename = Path.Combine(curBuildDirectory, PlayerSettings.productName + ".sln");

                    if (File.Exists(slnFilename))
                    {
                        var slnFile = new FileInfo(slnFilename);
                        Process.Start(slnFile.FullName);
                    }
                    else if (EditorUtility.DisplayDialog("Solution Not Found", "We couldn't find the solution. Would you like to Build it?", "Yes, Build", "No"))
                    {
                        // Build SLN
                        EditorApplication.delayCall += () => { BuildDeployTools.BuildSLN(curBuildDirectory); };
                    }
                }

                GUI.enabled = ShouldBuildSLNBeEnabled;

                if (GUILayout.Button("Build Visual Studio SLN", GUILayout.Width(buttonWidth_Half)))
                {
                    // Build SLN
                    EditorApplication.delayCall += () => { BuildDeployTools.BuildSLN(curBuildDirectory); };
                }

                GUI.enabled = true;
            }

            // Appx sub-section
            GUILayout.BeginVertical();
            GUILayout.Label("APPX");

            // SDK and MS Build Version(and save setting, if it's changed)
            string curMSBuildVer = BuildDeployPrefs.MsBuildVersion;
            string currentSDKVersion = EditorUserBuildSettings.wsaUWPSDK;

            int currentSDKVersionIndex = 0;
            int defaultMSBuildVersionIndex = 0;

            for (var i = 0; i < windowsSdkPaths.Length; i++)
            {
                if (string.IsNullOrEmpty(currentSDKVersion))
                {
                    currentSDKVersionIndex = windowsSdkPaths.Length - 1;
                }
                else
                {
                    if (windowsSdkPaths[i].Equals(currentSDKVersion))
                    {
                        currentSDKVersionIndex = i;
                    }

                    if (windowsSdkPaths[i].Equals("10.0.14393.0"))
                    {
                        defaultMSBuildVersionIndex = i;
                    }
                }
            }

            currentSDKVersionIndex = EditorGUILayout.Popup(GUIHorizSpacer + "SDK Version", currentSDKVersionIndex, windowsSdkPaths);

            string newSDKVersion = windowsSdkPaths[currentSDKVersionIndex];

            if (!newSDKVersion.Equals(currentSDKVersion))
            {
                EditorUserBuildSettings.wsaUWPSDK = newSDKVersion;
            }

            string newMSBuildVer = currentSDKVersionIndex <= defaultMSBuildVersionIndex ? BuildDeployTools.DefaultMSBuildVersion : "15.0";
            EditorGUILayout.LabelField(GUIHorizSpacer + "MS Build Version", newMSBuildVer);

            if (!newMSBuildVer.Equals(curMSBuildVer))
            {
                BuildDeployPrefs.MsBuildVersion = newMSBuildVer;
                curMSBuildVer = newMSBuildVer;
            }

            // Build config (and save setting, if it's changed)
            string curBuildConfigString = BuildDeployPrefs.BuildConfig;

            BuildConfigEnum buildConfigOption;
            if (curBuildConfigString.ToLower().Equals("master"))
            {
                buildConfigOption = BuildConfigEnum.MASTER;
            }
            else if (curBuildConfigString.ToLower().Equals("release"))
            {
                buildConfigOption = BuildConfigEnum.RELEASE;
            }
            else
            {
                buildConfigOption = BuildConfigEnum.DEBUG;
            }

            buildConfigOption = (BuildConfigEnum)EditorGUILayout.EnumPopup(GUIHorizSpacer + "Build Configuration", buildConfigOption);

            string newBuildConfig = buildConfigOption.ToString();

            if (newBuildConfig != curBuildConfigString)
            {
                BuildDeployPrefs.BuildConfig = newBuildConfig;
                curBuildConfigString = newBuildConfig;
            }

            // Build APPX button
            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.FlexibleSpace();

                float previousLabelWidth = EditorGUIUtility.labelWidth;

                // Force rebuild
                EditorGUIUtility.labelWidth = 50;
                bool curForceRebuildAppx = BuildDeployPrefs.ForceRebuild;
                bool newForceRebuildAppx = EditorGUILayout.Toggle("Rebuild", curForceRebuildAppx);

                if (newForceRebuildAppx != curForceRebuildAppx)
                {
                    BuildDeployPrefs.ForceRebuild = newForceRebuildAppx;
                    curForceRebuildAppx = newForceRebuildAppx;
                }

                // Increment version
                EditorGUIUtility.labelWidth = 110;
                bool curIncrementVersion = BuildDeployPrefs.IncrementBuildVersion;
                bool newIncrementVersion = EditorGUILayout.Toggle("Increment version", curIncrementVersion);

                if (newIncrementVersion != curIncrementVersion)
                {
                    BuildDeployPrefs.IncrementBuildVersion = newIncrementVersion;
                    curIncrementVersion = newIncrementVersion;
                }

                // Restore previous label width
                EditorGUIUtility.labelWidth = previousLabelWidth;

                // Build APPX
                GUI.enabled = ShouldBuildAppxBeEnabled;

                if (GUILayout.Button("Build APPX from SLN", GUILayout.Width(buttonWidth_Half)))
                {
                    // Open SLN
                    string slnFilename = Path.Combine(curBuildDirectory, PlayerSettings.productName + ".sln");

                    if (File.Exists(slnFilename))
                    {
                        // Build APPX
                        EditorApplication.delayCall += () =>
                            BuildDeployTools.BuildAppxFromSLN(
                                PlayerSettings.productName,
                                curMSBuildVer,
                                curForceRebuildAppx,
                                curBuildConfigString,
                                curBuildDirectory,
                                curIncrementVersion);
                    }
                    else if (EditorUtility.DisplayDialog("Solution Not Found", "We couldn't find the solution. Would you like to Build it?", "Yes, Build", "No"))
                    {
                        // Build SLN then APPX
                        EditorApplication.delayCall += () => BuildAll(install: false);
                    }
                }

                GUI.enabled = true;
            }

            GUILayout.EndVertical();
            GUILayout.EndVertical();

            GUILayout.Space(GUISectionOffset);

            // Deploy section
            GUILayout.BeginVertical();
            GUILayout.Label("Deploy");

            // Target IPs (and save setting, if it's changed)
            string curTargetIps = BuildDeployPrefs.TargetIPs;
            if (!LocalIPsOnly)
            {
                string newTargetIPs = EditorGUILayout.TextField(
                    new GUIContent(GUIHorizSpacer + "IP Address(es)", "IP(s) of target devices (e.g. 127.0.0.1;10.11.12.13)"),
                    curTargetIps);

                if (newTargetIPs != curTargetIps)
                {
                    BuildDeployPrefs.TargetIPs = newTargetIPs;
                    curTargetIps = newTargetIPs;
                }
            }
            else
            {
                // Queue up a repaint if we're still busy, or we'll get stuck
                // in a disabled state.

                if (locatorIsSearching)
                {
                    Repaint();
                }

                var addressesToPresent = new List<string> { "127.0.0.1" };

                if (!locatorIsSearching && locatorHasData)
                {
                    addressesToPresent.Add(xdeGuestIpAddress.ToString());
                }

                var previouslySavedAddress = addressesToPresent.IndexOf(curTargetIps);

                if (previouslySavedAddress == -1)
                {
                    previouslySavedAddress = 0;
                }

                EditorGUILayout.BeginHorizontal();

                if (locatorIsSearching && !locatorHasData)
                {
                    GUI.enabled = false;
                }

                var selectedAddressIndex = EditorGUILayout.Popup(GUIHorizSpacer + "IP Address", previouslySavedAddress, addressesToPresent.ToArray());

                if (GUILayout.Button(locatorIsSearching ? "Searching" : "Refresh", GUILayout.Width(buttonWidth_Quarter)))
                {
                    UpdateXdeStatus();
                }

                GUI.enabled = true;
                EditorGUILayout.EndHorizontal();

                var selectedAddress = addressesToPresent[selectedAddressIndex];

                if (curTargetIps != selectedAddress && !locatorIsSearching)
                {
                    BuildDeployPrefs.TargetIPs = selectedAddress;
                }
            }

            // Username/Preplacedword (and save seeings, if changed)
            string curUsername = BuildDeployPrefs.DeviceUser;
            string newUsername = EditorGUILayout.TextField(GUIHorizSpacer + "Username", curUsername);
            string curPreplacedword = BuildDeployPrefs.DevicePreplacedword;
            string newPreplacedword = EditorGUILayout.PreplacedwordField(GUIHorizSpacer + "Preplacedword", curPreplacedword);
            bool curFullReinstall = BuildDeployPrefs.FullReinstall;
            bool newFullReinstall = EditorGUILayout.Toggle(
                new GUIContent(GUIHorizSpacer + "Uninstall first", "Uninstall application before installing"), curFullReinstall);

            if (newUsername != curUsername ||
                newPreplacedword != curPreplacedword ||
                newFullReinstall != curFullReinstall)
            {
                BuildDeployPrefs.DeviceUser = newUsername;
                BuildDeployPrefs.DevicePreplacedword = newPreplacedword;
                BuildDeployPrefs.FullReinstall = newFullReinstall;
            }

            // Build list (with install buttons)
            if (builds.Count == 0)
            {
                GUILayout.Label(GUIHorizSpacer + "*** No builds found in build directory", EditorStyles.boldLabel);
            }
            else
            {
                GUILayout.BeginVertical();
                scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(buttonWidth_Full), GUILayout.Height(128));

                foreach (var fullBuildLocation in builds)
                {
                    int lastBackslashIndex = fullBuildLocation.LastIndexOf("\\", StringComparison.Ordinal);

                    var directoryDate = Directory.GetLastWriteTime(fullBuildLocation).ToString("yyyy/MM/dd HH:mm:ss");
                    string packageName = fullBuildLocation.Substring(lastBackslashIndex + 1);

                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Space(GUISectionOffset + 15);

                    GUI.enabled = (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
                    if (GUILayout.Button("Install", GUILayout.Width(120.0f)))
                    {
                        string thisBuildLocation = fullBuildLocation;
                        string[] ipList = ParseIPList(curTargetIps);
                        EditorApplication.delayCall += () =>
                        {
                            InstallAppOnDevicesList(thisBuildLocation, ipList);
                        };
                    }

                    GUI.enabled = true;

                    GUILayout.Space(5);
                    GUILayout.Label(packageName + " (" + directoryDate + ")");
                    EditorGUILayout.EndHorizontal();
                }
                GUILayout.EndScrollView();
                GUILayout.EndVertical();

                EditorGUILayout.Separator();
            }

            GUILayout.EndVertical();
            GUILayout.Space(GUISectionOffset);

            // Utilities section
            GUILayout.BeginVertical();
            GUILayout.Label("Utilities");

            // Open AppX packages location
            using (new EditorGUILayout.HorizontalScope())
            {
                GUI.enabled = builds.Count > 0;

                GUILayout.FlexibleSpace();

                if (GUILayout.Button("Open APPX Packages Location", GUILayout.Width(buttonWidth_Full)))
                {
                    Process.Start("explorer.exe", "/open," + Path.GetFullPath(curBuildDirectory + "/" + PlayerSettings.productName + "/AppPackages"));
                }

                GUI.enabled = true;
            }

            // Open web portal
            using (new EditorGUILayout.HorizontalScope())
            {
                GUI.enabled = ShouldWebPortalBeEnabled && (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
                GUILayout.FlexibleSpace();

                if (GUILayout.Button("Open Device Portal", GUILayout.Width(buttonWidth_Full)))
                {
                    OpenWebPortalForIPs(curTargetIps);
                }

                GUI.enabled = true;
            }

            // Launch app..
            using (new EditorGUILayout.HorizontalScope())
            {
                GUI.enabled = ShouldLaunchAppBeEnabled && (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
                GUILayout.FlexibleSpace();

                if (GUILayout.Button("Launch Application", GUILayout.Width(buttonWidth_Full)))
                {
                    // If already running, kill it (button is a toggle)
                    if (IsAppRunning_FirstIPCheck(PlayerSettings.productName, curTargetIps))
                    {
                        KillAppOnIPs(curTargetIps);
                    }
                    else
                    {
                        LaunchAppOnIPs(curTargetIps);
                    }
                }

                GUI.enabled = true;
            }

            // Log file
            using (new EditorGUILayout.HorizontalScope())
            {
                GUI.enabled = ShouldLogViewBeEnabled && (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
                GUILayout.FlexibleSpace();

                if (GUILayout.Button("View Log File", GUILayout.Width(buttonWidth_Full)))
                {
                    OpenLogFileForIPs(curTargetIps);
                }

                GUI.enabled = true;
            }

            // Uninstall...
            using (new EditorGUILayout.HorizontalScope())
            {
                GUI.enabled = ShouldLogViewBeEnabled && (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
                GUILayout.FlexibleSpace();

                if (GUILayout.Button("Uninstall Application", GUILayout.Width(buttonWidth_Full)))
                {
                    EditorApplication.delayCall += () =>
                    {
                        UninstallAppOnDevicesList(ParseIPList(curTargetIps));
                    };
                }

                GUI.enabled = true;
            }

            //GUILayout.EndScrollView();
            GUILayout.EndVertical();
        }

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 : FormAbout.cs
with MIT License
from AndnixSH

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("https://github.com/AndnixSH/Il2CppDumper-GUI");
        }

See More Examples