System.Environment.GetCommandLineArgs()

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

629 Examples 7

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : aurelitec

private void EventMainFormLoad(object sender, EventArgs e)
        {
            try
            {
                // Initialize the random number generators for generating random areas and random colors
                ColorsCommon.RandomGenerator = new Random();

                // Get the bounds of all monitors
                this.Bounds = SystemInformation.VirtualScreen;

                // Save the current opacity
                this.lastUserOpacity = this.Opacity;

                // Finalize the menus (add the opacity track bar, the multi monitor support items, modernize the menu, etc.)
                this.FinalizeMenus();

                // Create the quick start form
                this.quickStartForm = QuickStartForm.Create(this);

                // Load settings from the default configuration file (and the focus areas if AutoRestoreAreas is true)
                this.LoadLayout(string.Empty, false);
                this.quickStartForm.EnsureOnscreen();

                // Load an optional configuration file if specified on the command line
                string[] args = Environment.GetCommandLineArgs();
                if (args.Length > 1)
                {
                    this.LoadLayout(args[1], true);
                }

                // Register the Pause/Resume hot key read from the configuration file, or the default one
                this.HotKeyString = string.IsNullOrEmpty(this.hotKeyString) ? GlobalHotkey.KeysToString(Keys.Control | Keys.F11) : this.hotKeyString;
            }
            finally
            {
                // Signal that the startup phase has ended
                this.afterStartup = true;
            }
        }

19 View Source File : CommandLineParser.cs
License : Apache License 2.0
Project Creator : beetlex-io

public static CommandLineParser GetCommandLineParser()
        {
            return GetCommandLineParser(System.Environment.GetCommandLineArgs());
        }

19 View Source File : BuildSLNUtilities.cs
License : MIT License
Project Creator : anderm

public static void ParseBuildCommandLine(ref BuildInfo buildInfo)
        {
            string[] arguments = Environment.GetCommandLineArgs();

            buildInfo.IsCommandLine = true;

            for (int i = 0; i < arguments.Length; ++i)
            {
                // Can't use -buildTarget which is something Unity already takes as an argument for something.
                if (string.Equals(arguments[i], "-duskBuildTarget", StringComparison.InvariantCultureIgnoreCase))
                {
                    buildInfo.BuildTarget = (BuildTarget)Enum.Parse(typeof(BuildTarget), arguments[++i]);
                }
                else if (string.Equals(arguments[i], "-wsaSDK", StringComparison.InvariantCultureIgnoreCase))
                {
                    string wsaSdkArg = arguments[++i];

                    buildInfo.WSASdk = (WSASDK)Enum.Parse(typeof(WSASDK), wsaSdkArg);
                }
                else if (string.Equals(arguments[i], "-wsaUwpSdk", StringComparison.InvariantCultureIgnoreCase))
                {
                    buildInfo.WSAUwpSdk = arguments[++i];
                }
                else if (string.Equals(arguments[i], "-wsaUWPBuildType", StringComparison.InvariantCultureIgnoreCase))
                {
                    buildInfo.WSAUWPBuildType = (WSAUWPBuildType)Enum.Parse(typeof(WSAUWPBuildType), arguments[++i]);
                }
                else if (string.Equals(arguments[i], "-wsaGenerateReferenceProjects", StringComparison.InvariantCultureIgnoreCase))
                {
                    buildInfo.WSAGenerateReferenceProjects = bool.Parse(arguments[++i]);
                }
                else if (string.Equals(arguments[i], "-buildOutput", StringComparison.InvariantCultureIgnoreCase))
                {
                    buildInfo.OutputDirectory = arguments[++i];
                }
                else if (string.Equals(arguments[i], "-buildDesc", StringComparison.InvariantCultureIgnoreCase))
                {
                    ParseBuildDescriptionFile(arguments[++i], ref buildInfo);
                }
                else if (string.Equals(arguments[i], "-unityBuildSymbols", StringComparison.InvariantCultureIgnoreCase))
                {
                    string newBuildSymbols = arguments[++i];
                    buildInfo.AppendSymbols(newBuildSymbols.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
                }
            }
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : audiamus

protected override async void OnActivated (EventArgs e) {
      base.OnActivated (e);

      if (_initDone)
        return;
      _initDone = true;

      _pgaNaming.Update ();

      showWhatsNew ();

      makeFilereplacedoc ();

      checkAudibleActivationCode ();

      showStartupHint ();

      enableAll (true);
      var args = Environment.GetCommandLineArgs ();
      if (args.Length > 1)
        addFile (args[1]);

      await ensureFFmpegPathAsync ();
    }

19 View Source File : Car.cs
License : MIT License
Project Creator : arafattehsin

public static string GetPredictedResult(string buying, string maintenance, string doors, string persons, string lugboot, string safety)
            {
                buying = ValueMapper(buying);
                maintenance = ValueMapper(maintenance);
                doors = ValueMapper(doors);
                persons = ValueMapper(persons);
                lugboot = ValueMapper(lugboot);
                safety = ValueMapper(safety);

                CarEval carEval = new CarEval() { Buying = buying, Maintenance = maintenance, Doors = doors, Persons = persons, LugBoot = lugboot, Safety = safety };

                // Load model 
                string appPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
                string modelPath = Path.Combine(appPath, "CarEvaluator.zip");

                // Read model
                var model = PredictionModel.ReadAsync<CarEval, CarEvalPredictor>(modelPath).Result;

                // Predict car value
                var prediction = model.Predict(carEval);

                // Return to the caller
                return ValueMapper(prediction.Result);
            }

19 View Source File : Program.cs
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx

static string GetQuotedArgs()
        {
            string args = "";
            string currArg;
            foreach (var arg in Environment.GetCommandLineArgs().Skip(1))
            {
                currArg = arg;
                if (currArg.Contains(" "))
                {
                    currArg = "\"" + currArg + "\"";
                }

                args += currArg + " ";
            }

            return args;
        }

19 View Source File : UpdateHandler.cs
License : MIT License
Project Creator : AyrA

public static bool Update()
        {
            var Args = Environment.GetCommandLineArgs();
            //No update arguments
            if (Args.Length < 4 || Args[1] != "update" || !File.Exists(Args[3]))
            {
                Log.Write("Auto Update: No automatic update arguments found.");
                return false;
            }
            //Args:
            //0: Current file name
            //1: "update"
            //2: update step (1 or 2)
            //3: File name of target
            switch (Args[2])
            {
                case "1":
                    //Step 1 is performed by the temporary executable:
                    //1. copy itself (new version) over the old file name
                    //2. Run the old file name (now new file) with step 2
                    //3. Exit
                    try
                    {
                        if (WaitAndCopy(Args[0], Args[3], 5000))
                        {
                            //Start step 2
                            Process.Start(Args[3], $"update 2 \"{Args[0]}\"");
                            //C# doesn't "knows" that above line will exit
                            return true;
                        }
                        throw new IOException($"Timeout when trying to copy \"{Args[0]}\" to \"{Args[3]}\"");
                    }
                    catch (Exception ex)
                    {
                        Log.Write(new Exception("Unable to launch phase 2 of update", ex));
                    }
                    break;
                case "2":
                    //Step 2 is performed by the new version
                    //1. Delete temporary update file
                    //2. Restart application without arguments
                    if (WaitAndDel(Args[3], 5000))
                    {
                        //Restart without any command line arguments
                        Process.Start(Args[0]);
                        return true;
                    }
                    Log.Write("Update Phase 2: Automatic update did not complete in time: Unable to delete {0}", Args[3]);
                    break;
                default:
                    Log.Write("Invalid automatic update arguments.");
                    break;
            }
            return false;
        }

19 View Source File : Plugin.cs
License : MIT License
Project Creator : Aeroluna

[Init]
        public void Init(IPALogger pluginLogger)
        {
            string[] arguments = System.Environment.GetCommandLineArgs();
            foreach (string arg in arguments)
            {
                if (arg.ToLower() == "-replaceddump")
                {
                    replacedDump = true;
                    Logger.Log("[-replaceddump] launch argument detected, running in replaced Dump mode.");
                }
            }

            Logger = new HeckLogger(pluginLogger);
            SettingsSetter.SettingSetterSettableSettingsManager.SetupSettingsTable();
            SceneManager.activeSceneChanged += OnActiveSceneChanged;
        }

19 View Source File : Window.cs
License : MIT License
Project Creator : BluestormDNA

private string GetDiskFilename() {
            var cla = Environment.GetCommandLineArgs();
            if (cla.Any(s => s.EndsWith(".bin") || s.EndsWith(".cue") || s.EndsWith(".exe"))) {
                string filename = cla.First(s => s.EndsWith(".bin") || s.EndsWith(".cue") || s.EndsWith(".exe"));
                return filename;
            } else {
                //Show the user a dialog so they can pick the bin they want to load.
                var fileDialog = new OpenFileDialog();
                fileDialog.Filter = "BIN/CUE files or PSXEXEs(*.bin, *.cue, *.exe)|*.bin;*.cue;*.exe";
                fileDialog.ShowDialog();

                string file = fileDialog.FileName;
                return file;
            }
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : ajayyy

public static bool HasCommandLineArgument( string argumentName )
		{
			string[] args = System.Environment.GetCommandLineArgs();
			for ( int i = 0; i < args.Length; i++ )
			{
				if ( args[i].Equals( argumentName ) )
				{
					return true;
				}
			}

			return false;
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : atenfyr

[STAThread]
        static void Main()
        {
            if (Environment.OSVersion.Version.Major >= 6) SetProcessDPIAware();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            string[] args = Environment.GetCommandLineArgs();
            if (args.Length >= 2)
            {
                switch (args[1].ToLowerInvariant())
                {
                    // tojson <source> <destination> <engine version>
                    // UreplacedetGUI tojson A.umap B.json 514
                    case "tojson":
                        if (args.Length < 5) break;
                        UE4Version selectedVer = UE4Version.UNKNOWN;
                        if (!Enum.TryParse(args[4], out selectedVer))
                        {
                            if (int.TryParse(args[4], out int selectedVerRaw)) selectedVer = (UE4Version)selectedVerRaw;
                        }

                        string jsonSerializedreplacedet = new Ureplacedet(args[2], selectedVer).SerializeJson();
                        File.WriteAllText(args[3], jsonSerializedreplacedet);
                        return;
                    // fromjson <source> <destination>
                    // UreplacedetGUI fromjson B.json A.umap
                    case "fromjson":
                        if (args.Length < 4) break;
                        Ureplacedet jsonDeserializedreplacedet = null;
                        using (var sr = new FileStream(args[2], FileMode.Open))
                        {
                            jsonDeserializedreplacedet = Ureplacedet.DeserializeJson(sr);
                        }

                        if (jsonDeserializedreplacedet != null)
                        {
                            jsonDeserializedreplacedet.Write(args[3]);
                        }
                        return;
                }
            }

            Form1 f1 = new Form1
            {
                Size = new System.Drawing.Size(1000, 700)
            };
            Application.Run(f1);
        }

19 View Source File : MainWindowViewModel.cs
License : GNU General Public License v3.0
Project Creator : Artentus

private async void WindowOpenedHandler(object? sender, EventArgs e)
        {
            var args = Environment.GetCommandLineArgs();

            var parser = new Parser(config =>
            {
                config.CaseSensitive = false;
                config.HelpWriter = Console.Out;
            });
            var parsedOptions = parser.ParseArguments<RunOptions>(args);

            await parsedOptions.WithParsedAsync(EvaluateOptionsStartup);

#if !DEBUG
            await StartupUpdate();
#endif
        }

19 View Source File : App.cs
License : Apache License 2.0
Project Creator : alexyakunin

public void Run(Options options)
        {
            // Applying options
            if (!string.IsNullOrEmpty(options.GCLatencyMode))
                GCSettings.LatencyMode = Enum.Parse<GCLatencyMode>(options.GCLatencyMode);
            if (options.Duration.HasValue)
                BurnTester.DefaultDuration = TimeSpan.FromSeconds(options.Duration.Value);
            BurnTester.DefaultMaxSize = ArgumentHelper.ParseRelativeValue(
                options.MaxSize, BurnTester.DefaultMaxSize, true);
            ParallelRunner.ThreadCount = (int) ArgumentHelper.ParseRelativeValue(
                options.ThreadCount, ParallelRunner.ThreadCount, true);
            var tests = options.Tests?.ToLowerInvariant() ?? "";
            var ramSizeGb = HardwareInfo.GetRamSize() ?? 4;
            var staticSetSizeGb = 0;
            if (!string.IsNullOrEmpty(options.StaticSetSize)) {
                tests += "b";
                staticSetSizeGb = (int) ArgumentHelper.ParseRelativeValue(options.StaticSetSize, ramSizeGb, true);
            }
            var outputMode = options.OutputMode ?? "f";

            if (outputMode == "f") {
                // Dumping environment info
                Writer.AppendValue("Launch parameters", string.Join(" ", Environment.GetCommandLineArgs().Skip(1)));
                using (Writer.Section("Software:")) {
                    Writer.AppendValue("Runtime", ".NET Core");
                    using (Writer.Indent()) {
                        Writer.AppendValue("Version", RuntimeInformation.FrameworkDescription);
                        Writer.AppendValue("GC mode", GCInfo.GetGCMode());
                    }

                    Writer.AppendValue("OS",
                        $"{RuntimeInformation.OSDescription.Trim()} ({RuntimeInformation.OSArchitecture})");
                }

                using (Writer.Section("Hardware:")) {
                    var coreCountAddon = ParallelRunner.ThreadCount != Environment.ProcessorCount
                        ? $", {ParallelRunner.ThreadCount} used by test"
                        : "";
                    Writer.AppendValue("CPU", HardwareInfo.GetCpuModelName());
                    Writer.AppendValue("CPU core count", $"{Environment.ProcessorCount}{coreCountAddon}");
                    Writer.AppendValue("RAM size", $"{ramSizeGb:N0} GB");
                }
                Writer.AppendLine();
            }
            
            RunWarmup();

            if (tests == "") {
                RunSpeedTest();
                RunBurnTest("--- Stateless server (no static set) ---", 0);
                RunBurnTest("--- Worker / typical server (static set = 20% RAM) ---", (long) (ramSizeGb * Sizes.GB / 5));
                RunBurnTest("--- Caching / compute server (static set = 50% RAM) ---", (long) (ramSizeGb * Sizes.GB / 2));
                return;
            }

            if (tests.Contains("a")) {
                RunSpeedTest();
            }
            if (tests.Contains("b")) {
                var replacedle = $"--- Static set = {staticSetSizeGb} GB ({staticSetSizeGb * 100.0 / ramSizeGb:0.##} % RAM) ---";
                RunBurnTest(replacedle, (long) (staticSetSizeGb * Sizes.GB));
            }
        }

19 View Source File : FPFCInstaller.cs
License : MIT License
Project Creator : Auros

public override void InstallBindings()
        {
            if (!Environment.GetCommandLineArgs().Any(a => a.ToLower() == FPFCToggle.Argument))
                return;

            Container.BindInterfacesTo<FPFCToggle>().replacedingle();
        }

19 View Source File : UwpPlayerBuildTools.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static void ParseBuildCommandLine(ref UwpBuildInfo buildInfo)
        {
            IBuildInfo iBuildInfo = buildInfo;
            UnityPlayerBuildTools.ParseBuildCommandLine(ref iBuildInfo);

            string[] arguments = Environment.GetCommandLineArgs();

            for (int i = 0; i < arguments.Length; ++i)
            {
                switch (arguments[i])
                {
                    case "-buildAppx":
                        buildInfo.BuildAppx = true;
                        break;
                    case "-rebuildAppx":
                        buildInfo.RebuildAppx = true;
                        break;
                    case "-targetUwpSdk":
                        // Note: the min sdk target cannot be changed.
                        EditorUserBuildSettings.wsaUWPSDK = arguments[++i];
                        break;
                }
            }
        }

19 View Source File : AgentTester.cs
License : MIT License
Project Creator : Avanade

public static IConfiguration BuildConfiguration<TStartup>(string? environmentVariablePrefix = null, string? environment = TestSetUp.DefaultEnvironment) where TStartup : clreplaced
        {
            var cb = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile(new EmbeddedFileProvider(typeof(TStartup).replacedembly), $"webapisettings.json", true, false)
                .AddJsonFile(new EmbeddedFileProvider(typeof(TStartup).replacedembly), $"webapisettings.{environment}.json", true, false)
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{environment}.json", true, true);

            var evp = string.IsNullOrEmpty(environmentVariablePrefix) ? TestSetUp.DefaultEnvironmentVariablePrefix : environmentVariablePrefix;
            if (string.IsNullOrEmpty(evp))
                cb.AddEnvironmentVariables();
            else
                cb.AddEnvironmentVariables(evp.EndsWith("_", StringComparison.InvariantCulture) ? evp : evp + "_");

            var args = Environment.GetCommandLineArgs();
            cb.AddCommandLine(args);

            var config = cb.Build();
            if (config.GetValue<bool>("UseUserSecrets"))
                cb.AddUserSecrets<TStartup>();

            var kvn = config["KeyVaultName"];
            if (!string.IsNullOrEmpty(kvn))
            {
                var astp = new AzureServiceTokenProvider();
#pragma warning disable CA2000 // Dispose objects before losing scope; this object MUST NOT be disposed or will result in further error - only a single instance so is OK.
                var kvc = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(astp.KeyVaultTokenCallback));
                cb.AddAzureKeyVault($"https://{kvn}.vault.azure.net/", kvc, new DefaultKeyVaultSecretManager());
#pragma warning restore CA2000
            }

            cb.AddCommandLine(args);

            return cb.Build();
        }

19 View Source File : SingleInstance.cs
License : GNU General Public License v3.0
Project Creator : Amebis

private static IList<string> GetCommandLineArgs(string uniqueApplicationName)
        {
            string[] args = null;
            if (AppDomain.CurrentDomain.ActivationContext == null)
            {
                // The application was not clickonce deployed, get args from standard API's
                args = Environment.GetCommandLineArgs();
            }
            else
            {
                // The application was clickonce deployed
                // Clickonce deployed apps cannot recieve traditional commandline arguments
                // As a workaround commandline arguments can be written to a shared location before 
                // the app is launched and the app can obtain its commandline arguments from the 
                // shared location               
                string appFolderPath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), uniqueApplicationName);

                string cmdLinePath = Path.Combine(appFolderPath, "cmdline.txt");
                if (File.Exists(cmdLinePath))
                {
                    try
                    {
                        using (TextReader reader = new StreamReader(cmdLinePath, System.Text.Encoding.Unicode))
                        {
                            args = NativeMethods.CommandLineToArgvW(reader.ReadToEnd());
                        }

                        File.Delete(cmdLinePath);
                    }
                    catch (IOException)
                    {
                    }
                }
            }

            if (args == null)
            {
                args = new string[] { };
            }

            return new List<string>(args);
        }

19 View Source File : ArgumentsContext.cs
License : MIT License
Project Creator : b-editor

public static async ValueTask ExecuteAsync()
        {
            if (IsExecuted) return;

            await Dispatcher.UIThread.InvokeAsync(() => GetAction(Environment.GetCommandLineArgs()).Invoke());

            IsExecuted = true;
        }

19 View Source File : UnityStudioCLI.cs
License : MIT License
Project Creator : 91Act

static void Main()
        {
            var args = Environment.GetCommandLineArgs();
            if (args.Length > 1)
            {
                var cmd = args[1];
                var abPath = "";
                switch (cmd)
                {
                    case "--list":
                        if (args.Length>2){
                            abPath = args[2];
                            enableDebugPrint = false;
                            UnityStudio.LoadBundleFile(abPath,false,"");
                            return;
                        }
                        break;
                    case "--dump":
                    /*
                        Extract files inside replacedetbundle file to savePath.
                     */
                        var savePath = "";
                        if (args.Length>2){
                            abPath = args[2];
                            if (args.Length>3){
                                savePath = args[3];
                            }
                            UnityStudio.LoadBundleFile(abPath,true,savePath);
                            return;
                        }
                        break;
                    default:
                        break;
                }
            }
            Console.WriteLine("Unrecognized command:");
            for(int i=0;i<args.Length;i++){
                Console.WriteLine("CMD["+i+"]="+args[i].ToString());
            }
        }

19 View Source File : UMakeCli.cs
License : MIT License
Project Creator : bitcake

private static void GetArgs()
		{
			string[] allArgs = System.Environment.GetCommandLineArgs();

			if( allArgs == null )
				throw new CliErrorException( "No args provided." );

			foreach( var arg in allArgs )
			{
				int index = arg.IndexOf( ':' );
				if( index >= 0 )
					Args[arg.Substring( 0, index )] = arg.Substring( index + 1 );
			}

			IsInCli = true;
		}

19 View Source File : UpdateSettingsViewModel.cs
License : MIT License
Project Creator : AnnoDesigner

private async void ExecuteDownloadPresets(object param)
        {
            if (FoundPresetRelease is null)
            {
                return;
            }

            BusyContent = _localizationHelper.GetLocalization("UpdatePreferencesBusyDownloadPresets");
            IsBusy = true;

            if (!_commons.CanWriteInFolder())
            {
                //already asked for admin rights?
                if (Environment.GetCommandLineArgs().Any(x => x.Trim().Equals(Constants.Argument_Ask_For_Admin, StringComparison.OrdinalIgnoreCase)))
                {
                    _messageBoxService.ShowWarning($"You have no write access to the folder.{Environment.NewLine}The update can not be installed.",
                        _localizationHelper.GetLocalization("Error"));

                    IsBusy = false;
                    return;
                }

                _messageBoxService.ShowMessage(_localizationHelper.GetLocalization("UpdateRequiresAdminRightsMessage"),
                    _localizationHelper.GetLocalization("AdminRightsRequired"));

                _appSettings.Save();
                _commons.RestartApplication(true, Constants.Argument_Ask_For_Admin, App.ExecutablePath);
            }

            //Context is required here, do not use ConfigureAwait(false)
            var newLocation = await _updateHelper.DownloadReleaseAsync(FoundPresetRelease);
            logger.Debug($"downloaded new preset ({FoundPresetRelease.Version}): {newLocation}");

            IsBusy = false;

            _appSettings.Save();
            _commons.RestartApplication(false, null, App.ExecutablePath);

            Environment.Exit(-1);
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : antikmozib

[STAThread]
        static void Main()
        {
            String[] arguments = Environment.GetCommandLineArgs();
            if (arguments.Count() > 1)
            {
                if (arguments[1].ToLower() == "-debug")
                {
                    general.debugEnabled = true;
                }
                else
                {
                    general.debugEnabled = false;
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmMain());
        }

19 View Source File : MainWindow.cs
License : GNU General Public License v3.0
Project Creator : a4004

private async void Init()
        {
            if (Program.Portable)
                goto InitTaskEnd;
InitPyChk:
            WaitFm.Caption("Checking if Python is installed");
            await Task.Delay(1000);

            if (!ShellManager.CheckCommand("py", "--version"))
            {
                WaitFm.Debug("Python could not be detected on your system. You can choose to install Python or use N2D22 in portable mode.", Event.Warning);

                CreateRequest("Python isn't installed on this PC", "You can choose to install Python",
                    "Install Python 3.9.7 (Recommended)", "Portable mode (Legacy, not recommended)", out int result);

                if (result == 1 /*install python*/)
                {
                    WaitFm.Caption("Downloading Python x64 3.9.7");

                    try
                    {
                        WebClient client = new WebClient();

                        client.DownloadProgressChanged += (s, e) =>
                        {
                            WaitFm.Caption($"Downloading Python x64 3.9.7 from python.org ({e.ProgressPercentage}%)");
                        };
                        client.DownloadFileCompleted += delegate
                        {
                            WaitFm.Debug("Successfully downloaded python-3.9.7-amd64.exe from python.org", Event.Success);
                            WaitFm.Caption("Installing Python x64 3.9.7");
                        };

                        WaitFm.Debug("Downloading python-3.9.7-amd64.exe from python.org");
                        await client.DownloadFileTaskAsync("https://www.python.org/ftp/python/3.9.7/python-3.9.7-amd64.exe", "python-3.9.7-amd64.exe");

                        WaitFm.Caption("Installing Python");
                        WaitFm.Debug("Installing Python x64 3.9.7");

                        if (ShellManager.RunCommand(out string output, "python-3.9.7-amd64.exe", "/quiet InstallAllUsers=1 PrependPath=1"))
                        {
                            WaitFm.Caption("Verifying Python is installed");
                            WaitFm.Debug("Verifying Python x64 3.9.7", Event.Success);
                            WaitFm.replacedle("Preparing");
                            await Task.Delay(1000);

                            goto InitPyChk;
                        }
                        else
                            throw new Exception(output == default ? "Process not started." : output);
                    }
                    catch (Exception ex)
                    {
                        WaitFm.Debug($"Python could not be installed due to an error. {ex.Message}", Event.Critical);
                        await CreateMessage("We couldn't install Python", "Something went wrong during the install process. You can try again.");

                        WaitFm.Host.CloseTask();
                        WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                        TaskManager.ReleaseFLock();
                        return;
                    }
                }
                else if (result == 2 /*run in portable mode*/)
                {
                    Process.Start(Application.ExecutablePath, string.Join(" ", Environment.GetCommandLineArgs()) + " --portable");
                    Program.Terminate();
                    return;
                }
                else
                    throw new Exception($"The selection could not be determined due to an invalid value. {result}");
            }
            else
            {
                if (ShellManager.RunCommand(out string filePath, "py", "-c \"import sys; print(sys.executable)\""))
                    WaitFm.Debug($"Python is installed on this PC at \"{filePath}\".", Event.Success);
                else
                    WaitFm.Debug("Could not get the executable path of the Python binary.", Event.Warning);

                Program.Settings.PythonExe = filePath;

                WaitFm.replacedle("Getting ready");
                WaitFm.Caption("Checking for esptool.py");
                await Task.Delay(1000);

                if (!ShellManager.CheckCommand("py", "-m esptool --help"))
                {
                    WaitFm.Debug("esptool.py isn't installed in the default Python environment. " +
                        "You can choose to install esptool or use N2D22 in portable mode.");

                    CreateRequest("esptool.py is missing", "You can choose to install it right now",
                        "Install esptool.py (Recommended)", "Portable mode (Legacy, not recommended)", out int result);

                    if (result == 1 /*install esptool*/)
                    {
                        WaitFm.Debug("Installing esptool.py");
                        WaitFm.Caption("Installing esptool.py");

                        if (ShellManager.RunCommand(out string output, "py", "-m pip install esptool"))
                        {
                            WaitFm.Debug("esptool.py was installed successfully.");
                            WaitFm.replacedle("Preparing");
                            await Task.Delay(3000);

                            goto InitPyChk;
                        }
                    }
                    else if (result == 2 /*run in portable mode*/)
                    {
                        Process.Start(Application.ExecutablePath, string.Join(" ", Environment.GetCommandLineArgs()) + " --portable");
                        Program.Terminate();
                        return;
                    }
                    else
                        throw new Exception($"The selection could not be determined due to an invalid value. {result}");
                }
                else
                {
                    WaitFm.Caption("Making sure you're ready to flash");
                    WaitFm.Debug("esptool.py is installed in the default Python environment.");
                    Program.Settings.EsptoolPy = true;

                    await Task.Delay(1000);
                    WaitFm.Debug("Searching for device drivers.");
                    await Task.Delay(1000);

                    string silabserPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
                        .ToList().Where(o => o.Contains("silabser")).FirstOrDefault();
                    WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"silabser\"");
                    string ch34serPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
                        .ToList().Where(o => o.Contains("ch341ser")).FirstOrDefault();
                    WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ch34ser\"");
                    string ftdiPortPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
                        .ToList().Where(o => o.Contains("ftdiport")).FirstOrDefault();
                    WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ftdiport\"");
                    string ftdiBusPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
                        .ToList().Where(o => o.Contains("ftdibus")).FirstOrDefault();
                    WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ftdibus\"");

                    if (silabserPath == default && ch34serPath == default && ftdiPortPath == default && ftdiBusPath == default)
                    {
                        WaitFm.Debug("Driver files not found in FileRepository.", Event.Warning);

                        await CreateMessage("Device drivers not found", "We could not detect any Espressif compatible device drivers " +
                            "on this PC. You can still try flashing your device as Windows may automatically install the correct drivers " +
                            "for you.", 10);
                    }
                    else if (silabserPath != default && ch34serPath != default && ftdiPortPath != default && ftdiBusPath != default)
                    {
                        WaitFm.Debug("Detected drivers: SILABSER, CH34SER, FTDIPORT-FTDIBUS", Event.Success);

                        await CreateMessage("Found multiple device drivers", "We found device drivers for Silicon Labs, CH34 and FTDI compatible " +
                            "devices on this PC. The correct driver will automatically take control of your device when flashing.", 10);
                    }
                    else
                    {
                        if (silabserPath != default)
                        {
                            WaitFm.Debug("Detected driver: SILABSER", Event.Success);

                            await CreateMessage("Found device driver (Silicon Labs)", "We found a device driver for Silicon Labs devices on this PC. " +
                                "Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
                        }
                        if (ch34serPath != default)
                        {
                            WaitFm.Debug("Detected driver: CH34SER", Event.Success);

                            await CreateMessage("Found device driver (CH34)", "We found a device driver for CH34 devices on this PC. " +
                                "Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
                        }
                        if (ftdiBusPath != default && ftdiPortPath != default)
                        {
                            WaitFm.Debug("Detected driver: FTDIPORT-FTDIBUS", Event.Success);

                            await CreateMessage("Found device driver (FTDI)", "We found a device driver for FTDI devices on this PC. " +
                                "Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
                        }
                        else if (ftdiBusPath != default || ftdiPortPath != default)
                        {
                            WaitFm.Debug($"Detected partial driver: {(ftdiPortPath != default ? "FTDIPORT" : ftdiBusPath != default ? "FTDIBUS" : "?")}", Event.Warning);

                            await CreateMessage("Found device driver files (FTDI)", "We found parts of a device driver package for FTDU " +
                                "devices on this PC. The driver might not be installed correctly. Ensure the driver is correct and/or " +
                                "installed correctly.", 7);
                        }
                    }
                }
            }

InitTaskEnd:
            WaitFm.Caption(""); 
            await Task.Delay(1000);
            WaitFm.Host.CloseTask();

            WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
            TaskManager.ReleaseFLock();

            if (Program.Settings.PortFix)
            {
                Invoke(new Action(() =>
                {
                    mitigationNotice.Show();
                    CreateForegroundTask("devicescan-patch", new Task(delegate() { }), "", "Please connect your device to this PC. When you've confirmed it's connected, click Continue.");
                }));
            }
            else
            {
                Invoke(new Action(() =>
                {
                    CreateForegroundTask("devicescan", new Task(Search), "Searching for your device", "You should connect your device now");
                }));
            }
        }

19 View Source File : Car.cs
License : MIT License
Project Creator : arafattehsin

public string GetPredictedResult(string buying, string maintenance, string doors, string persons, string lugboot, string safety)
            {
                CarEval carEval = new CarEval() { Buying = buying, Maintenance = maintenance, Doors = doors, Persons = persons, LugBoot = lugboot, Safety = safety };

                // Load model 
                string appPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
                string modelPath = Path.Combine(appPath, "CarEvaluator.zip");

                // Read model
                var model = PredictionModel.ReadAsync<CarEval, CarEvalPredictor>(modelPath).Result;

                // Predict car value
                var prediction = model.Predict(carEval);

                // Return to the caller
                return prediction.Result;
            }

19 View Source File : Util.cs
License : MIT License
Project Creator : ajayyy

public static int GetCommandLineArgValue( string argumentName, int nDefaultValue )
		{
			string[] args = System.Environment.GetCommandLineArgs();
			for ( int i = 0; i < args.Length; i++ )
			{
				if ( args[i].Equals( argumentName ) )
				{
					if ( i == ( args.Length - 1 ) ) // Last arg, return default
					{
						return nDefaultValue;
					}

					return System.Int32.Parse( args[i + 1] );
				}
			}

			return nDefaultValue;
		}

19 View Source File : Form1.cs
License : MIT License
Project Creator : atenfyr

private void Form1_Load(object sender, EventArgs e)
        {
            UAGPalette.InitializeTheme();
            UAGPalette.RefreshTheme(this);

            string initialSelection = versionOptionsKeys[0];
            try
            {
                initialSelection = Properties.Settings.Default.PreferredVersion;
            }
            catch
            {
                initialSelection = versionOptionsKeys[0];
            }

            comboSpecifyVersion.Items.AddRange(versionOptionsKeys);
            comboSpecifyVersion.SelectedIndex = 0;

            for (int i = 0; i < versionOptionsKeys.Length; i++)
            {
                if (versionOptionsKeys[i] == initialSelection)
                {
                    comboSpecifyVersion.SelectedIndex = i;
                    break;
                }
            }

            UpdateComboSpecifyVersion();

            // Fetch the latest version from github
            Task.Run(() =>
            {
                latestOnlineVersion = GitHubAPI.GetLatestVersionFromGitHub(GitHubRepo);
            }).ContinueWith(res =>
            {
                if (latestOnlineVersion != null && latestOnlineVersion.IsUAGVersionLower())
                {
                    MessageBox.Show("A new version of UreplacedetGUI (v" + latestOnlineVersion + ") is available to download!");
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());

            // Command line parameter support
            string[] args = Environment.GetCommandLineArgs();
            if (args.Length > 1)
            {
                LoadFileAt(args[1]);
            }
        }

19 View Source File : Utility.cs
License : MIT License
Project Creator : Ashesh3

public static bool HreplacedtartOption(string option)
            => Environment.GetCommandLineArgs().Any(x => x?.ToLower() == option.ToLower());

19 View Source File : MainWindow.xaml.cs
License : Apache License 2.0
Project Creator : AlexWan

private void CommandLineInterfaceProcess()
        {
            string[] args = Environment.GetCommandLineArgs();
            if (Array.Exists(args, a => a.Equals("-robots")))
            {
                ButtonRobotCandleOne_Click(this, default);
            }
            else if (Array.Exists(args, a => a.Equals("-tester")))
            {
                ButtonTesterCandleOne_Click(this, default);
            }
        }

19 View Source File : BuildScripts.cs
License : Apache License 2.0
Project Creator : atteneder

[MenuItem("glTF Demo/Build WebGL")]
        public static void BuildWebPlayer() {

            // var scenes = EditorBuildSettings.scenes;
            // var scenePaths = new string[scenes.Length];
            // for (var i = 0; i < scenes.Length; i++) {
            //     scenePaths[i] = scenes[i].path;
            // }

            var scenePaths = new[] {
                "Packages/com.atteneder.gltf-demo/Runtime/Scenes/TestLoadScene.unity"
            };

            string buildPath = null;
            var args = System.Environment.GetCommandLineArgs ();
            for (var i = 0; i < args.Length; i++) {
                if (args[i] == "-buildPath" && i<=args.Length) {
                    buildPath = args[i + 1];
                    break;
                }
            }
            
            if (buildPath == null) {
                buildPath = EditorUtility.SaveFolderPanel(
                    "glTF demo build path",
                    null,
                    $"glTFast"
                );
            }
            
            if (string.IsNullOrEmpty(buildPath)) {
                return;
            }
            else {
                Debug.Log($"Building at build path {buildPath}");
            }
            
            var buildPlayerOptions = new BuildPlayerOptions {
                scenes = scenePaths,
                locationPathName = buildPath,
                target = BuildTarget.WebGL,
                options = BuildOptions.None
            };

            var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
            var summary = report.summary;

            switch (summary.result) {
                case BuildResult.Succeeded:
                    Debug.Log("Build succeeded: " + summary.totalSize + " bytes");
                    break;
                case BuildResult.Failed:
                    Debug.LogError("Build failed");
                    break;
                case BuildResult.Unknown:
                    Debug.LogError("Build result unknown");
                    break;
                case BuildResult.Cancelled:
                    Debug.Log("Build canceled");
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

19 View Source File : UnityPlayerBuildTools.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static void ParseBuildCommandLine(ref IBuildInfo buildInfo)
        {
            string[] arguments = Environment.GetCommandLineArgs();

            for (int i = 0; i < arguments.Length; ++i)
            {
                switch (arguments[i])
                {
                    case "-autoIncrement":
                        buildInfo.AutoIncrement = true;
                        break;
                    case "-sceneList":
                        buildInfo.Scenes = buildInfo.Scenes.Union(SplitSceneList(arguments[++i]));
                        break;
                    case "-sceneListFile":
                        string path = arguments[++i];
                        if (File.Exists(path))
                        {
                            buildInfo.Scenes = buildInfo.Scenes.Union(SplitSceneList(File.ReadAllText(path)));
                        }
                        else
                        {
                            Debug.LogWarning($"Scene list file at '{path}' does not exist.");
                        }
                        break;
                    case "-buildOutput":
                        buildInfo.OutputDirectory = arguments[++i];
                        break;
                    case "-colorSpace":
                        buildInfo.ColorSpace = (ColorSpace)Enum.Parse(typeof(ColorSpace), arguments[++i]);
                        break;
                    case "-scriptingBackend":
                        buildInfo.ScriptingBackend = (ScriptingImplementation)Enum.Parse(typeof(ScriptingImplementation), arguments[++i]);
                        break;
                    case "-x86":
                    case "-x64":
                    case "-arm":
                    case "-arm64":
                        buildInfo.BuildPlatform = arguments[i].Substring(1);
                        break;
                    case "-debug":
                    case "-master":
                    case "-release":
                        buildInfo.Configuration = arguments[i].Substring(1).ToLower();
                        break;
                    case "-logDirectory":
                        buildInfo.LogDirectory = arguments[++i];
                        break;
                }
            }
        }

19 View Source File : CLIUtils.cs
License : MIT License
Project Creator : attilioHimeki

public static string GetCommandLineArg(string arg)
    {
        var args = System.Environment.GetCommandLineArgs();

        for (int i = 0; i < args.Length; i++)
        {
            if (args[i] == arg)
            {
                return args[i + 1];
            }
        }

        return string.Empty;
    }

19 View Source File : PackageUpdateHandler.cs
License : Apache License 2.0
Project Creator : Algoryx

private static void PostReload()
    {
      EditorApplication.LockReloadreplacedemblies();

      try {
        Debug.Log( "Verifying native libraries aren't loaded..." );
        {
          var processModules  = Process.GetCurrentProcess().Modules;
          var nativePluginsId = new DirectoryInfo( IO.Utils.AGXUnityPluginDirectory );
          foreach ( ProcessModule processModule in processModules ) {
            if ( processModule.FileName.Contains( nativePluginsId.FullName ) )
              throw new System.Exception( $"AGX Dynamics module {processModule.ModuleName} is loaded. Unable to install new version of package." );
          }
        }

        var packageName = string.Empty;
        foreach ( var arg in System.Environment.GetCommandLineArgs() ) {
          if ( arg.StartsWith( s_packageIdentifier ) )
            packageName = arg.Substring( s_packageIdentifier.Length );
        }

        if ( string.IsNullOrEmpty( packageName ) )
          throw new System.Exception( $"Unable to find package name identifier {s_packageIdentifier} in arguments list: " +
                                      string.Join( " ", System.Environment.GetEnvironmentVariables() ) );

        Debug.Log( "Removing old native binaries..." );
        foreach ( var nativePlugin in NativePlugins ) {
          var fi = new FileInfo( nativePlugin.replacedetPath );
          Debug.Log( $"    - {fi.Name}" );
          var fiMeta = new FileInfo( nativePlugin.replacedetPath + ".meta" );
          try {
            fi.Delete();
            if ( fiMeta.Exists )
              fiMeta.Delete();
          }
          catch ( System.Exception ) {
            Debug.LogError( "Fatal update error: Close Unity and remove AGX Dynamics for Unity directory and install the latest version." );
            throw;
          }
        }

        var newPackageFileInfo = new FileInfo( packageName );
        if ( newPackageFileInfo.Name.EndsWith( "_Plugins_x86_64.unitypackage" ) ) {
          // Manager is loaded when the binaries hasn't been added and ExternalAGXInitializer
          // pops up and asks if the user would like to located AGX Dynamics. We're
          // installing the binaries so it's a "user said no!" to begin with.
          ExternalAGXInitializer.UserSaidNo = true;

          var dataDirectory = IO.Utils.AGXUnityPluginDirectory +
                              Path.DirectorySeparatorChar +
                              "agx";
          if ( Directory.Exists( dataDirectory ) ) {
            var directoryHandler = new IO.DirectoryContentHandler( dataDirectory );
            Debug.Log( $"Removing AGX Dynamics data directory {directoryHandler.RootDirectory}..." );
            directoryHandler.DeleteAllCollected();
          }
        }
        else {
          Debug.Log( "Removing all non-user specific content..." );
          IO.DirectoryContentHandler.DeleteContent();
        }

        // This will generate compile errors from scripts using AGXUnity and
        // we don't know how to hide these until we're done, mainly because
        // we have no idea when we're done with the update.
        // 
        // If this isn't performed, the compiler will throw exception due
        // to missing references and Unity will crash the first time we
        // use AGX Dynamics.
        replacedetDatabase.Refresh();

        Debug.Log( $"Starting import of package: {packageName}" );
        replacedetDatabase.ImportPackage( packageName, false );
      }
      catch ( System.Exception e ) {
        Debug.LogException( e );
      }

      Build.DefineSymbols.Remove( Build.DefineSymbols.ON_AGXUNITY_UPDATE );
      EditorApplication.UnlockReloadreplacedemblies();
    }

19 View Source File : SiraSettingsInstaller.cs
License : MIT License
Project Creator : Auros

public override void InstallBindings()
        {
            Container.BindInstance(_config.FPFCToggle).replacedingle();
            Container.BindInstance(_config.SongControl).replacedingle();
            Container.BindInterfacesTo<FPFCSettingsController>().replacedingle();

            if (Environment.GetCommandLineArgs().Any(a => a.ToLower() == FPFCToggle.Argument))
                Container.BindInterfacesTo<OriginalFPFCDisabler>().replacedingle().NonLazy();
        }

19 View Source File : GeneralEditorWindowBase.cs
License : MIT License
Project Creator : 404Lcc

[PropertySpace(10)]
        [LabelText("生成PC/Android/IOS文件"), Button]
        public void BuildPlayer()
        {
            List<string> argList = new List<string>();
            foreach (string item in Environment.GetCommandLineArgs())
            {
                argList.Add(item);
            }
            string name = $"{PlayerSettings.productName} v{PlayerSettings.bundleVersion}";
#if UNITY_STANDALONE
            name = $"{name}.exe";
#endif
#if UNITY_ANDROID
            name = $"{name}.apk";
#endif
            string locationPathName = $"{PathUtil.GetPath(PathType.PersistentDataPath, "Build")}/{name}";
            BuildPipeline.BuildPlayer(EditorBuildSettings.scenes, locationPathName, EditorUserBuildSettings.activeBuildTarget, EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None);
        }

19 View Source File : FormBackground.cs
License : MIT License
Project Creator : AutoItConsulting

private bool OptionsReadCommandLineAndOptionsFile()
        {
            string[] arguments = Environment.GetCommandLineArgs();
            string optionsFilename = string.Empty;

            if (arguments.Length >= 2)
            {
                string arg = arguments[1].ToUpper();

                if (arg == "/?" || arg == "?")
                {
                    var usage = @"AutoIt.OSD.Background [/Close] | [Options.xml]";
                    MessageBox.Show(usage, Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }

                if (arg == "/CLOSE" || arg == "CLOSE")
                {
                    // If we are not the first instance, send a quit message along the pipe
                    if (!IsApplicationFirstInstance())
                    {
                        //KillPreviousInstance();
                        var namedPipeXmlPayload = new NamedPipeXmlPayload
                        {
                            SignalQuit = true
                        };

                        NamedPipeClientSendOptions(namedPipeXmlPayload);
                    }

                    return false;
                }

                // Get the options filename
                optionsFilename = arguments[1];
            }

            // If no filename specified, use options.xml in current folder
            if (arguments.Length == 1)
            {
                optionsFilename = _appPath + @"\Options.xml";
            }

            try
            {
                var deSerializer = new XmlSerializer(typeof(Options));
                TextReader reader = new StreamReader(optionsFilename);
                _options = (Options)deSerializer.Deserialize(reader);
                _options.SanityCheck();
            }
            catch (Exception e)
            {
                string message = Resources.UnableToParseXml;

                if (e.InnerException != null)
                {
                    message += "\n\n" + e.InnerException.Message;
                }

                MessageBox.Show(message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            // Additional parsing of some string values in useful fields
            if (!OptionsXmlOptionsObjectToFields(_options))
            {
                return false;
            }

            // If are not the first instance then send a message to the running app with the new options and then quit
            if (!IsApplicationFirstInstance())
            {
                var namedPipeXmlPayload = new NamedPipeXmlPayload
                {
                    SignalQuit = false,
                    OsdBackgroundDir = _osdBackgroundDir,
                    OsdBackgroundWorkingDir = Directory.GetCurrentDirectory(),
                    Options = _options
                };

                NamedPipeClientSendOptions(namedPipeXmlPayload);
                return false;
            }

            return true;
        }

19 View Source File : SelfUpdateProgressPage.cs
License : GNU General Public License v3.0
Project Creator : Amebis

public override void OnActivate()
        {
            base.OnActivate();

            // Setup self-update.
            var selfUpdate = new BackgroundWorker() { WorkerReportsProgress = true };
            selfUpdate.DoWork += (object sender, DoWorkEventArgs e) =>
            {
                selfUpdate.ReportProgress(0);
                var random = new Random();
                var tempFolder = Path.GetTempPath();
                var workingFolder = tempFolder + Path.GetRandomFileName() + "\\";
                Directory.CreateDirectory(workingFolder);
                try
                {
                    string installerFilename = null;
                    FileStream installerFile = null;

                    // Download installer.
                    while (DownloadUris.Count > 0)
                    {
                        Window.Abort.Token.ThrowIfCancellationRequested();
                        var uriIndex = random.Next(DownloadUris.Count);
                        try
                        {
                            var binaryUri = DownloadUris[uriIndex];
                            Trace.TraceInformation("Downloading installer file from {0}...", binaryUri.AbsoluteUri);
                            var request = WebRequest.Create(binaryUri);
                            request.Proxy = null;
                            using (var response = request.GetResponse())
                            {
                                // 1. Get installer filename from Content-Disposition header.
                                // 2. Get installer filename from the last segment of URI path.
                                // 3. Fallback to a predefined installer filename.
                                try { installerFilename = Path.GetFullPath(workingFolder + new ContentDisposition(request.Headers["Content-Disposition"]).FileName); }
                                catch
                                {
                                    try { installerFilename = Path.GetFullPath(workingFolder + binaryUri.Segments[binaryUri.Segments.Length - 1]); }
                                    catch { installerFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup.exe"); }
                                }

                                // Save response data to file.
                                installerFile = File.Open(installerFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
                                try
                                {
                                    using (var stream = response.GetResponseStream())
                                    {
                                        installerFile.Seek(0, SeekOrigin.Begin);
                                        var hash = new eduEd25519.SHA256();
                                        var buffer = new byte[1048576];
                                        long offset = 0, total = response.ContentLength;

                                        for (; ; )
                                        {
                                            // Wait for the data to arrive.
                                            Window.Abort.Token.ThrowIfCancellationRequested();
                                            var bufferLength = stream.Read(buffer, 0, buffer.Length);
                                            if (bufferLength == 0)
                                                break;
                                            //Window.Abort.Token.WaitHandle.WaitOne(100); // Mock a slow link for testing.

                                            // Append it to the file and hash it.
                                            Window.Abort.Token.ThrowIfCancellationRequested();
                                            installerFile.Write(buffer, 0, bufferLength);
                                            hash.TransformBlock(buffer, 0, bufferLength, buffer, 0);

                                            // Report progress.
                                            offset += bufferLength;
                                            selfUpdate.ReportProgress((int)(offset * 100 / total));
                                        }

                                        hash.TransformFinalBlock(buffer, 0, 0);
                                        if (!hash.Hash.SequenceEqual(Hash))
                                            throw new DownloadedFileCorruptException(string.Format(Resources.Strings.ErrorDownloadedFileCorrupt, binaryUri.AbsoluteUri));

                                        installerFile.SetLength(installerFile.Position);
                                        break;
                                    }
                                }
                                catch
                                {
                                    // Close installer file.
                                    installerFile.Close();
                                    installerFile = null;

                                    // Delete installer file. If possible.
                                    Trace.TraceInformation("Deleting file {0}...", installerFilename);
                                    try { File.Delete(installerFilename); }
                                    catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }
                                    installerFilename = null;

                                    throw;
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception ex)
                        {
                            Trace.TraceWarning("Error: {0}", ex.ToString());
                            DownloadUris.RemoveAt(uriIndex);
                        }
                    }

                    if (installerFilename == null || installerFile == null)
                    {
                        // The installer file is not ready.
                        throw new InstallerFileUnavailableException();
                    }

                    try
                    {
                        var updaterFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup and Relaunch.wsf");
                        var updaterFile = File.Open(updaterFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
                        try
                        {
                            // Prepare WSF file.
                            var writer = new XmlTextWriter(updaterFile, null);
                            writer.WriteStartDoreplacedent();
                            writer.WriteStartElement("package");
                            writer.WriteStartElement("job");

                            writer.WriteStartElement("reference");
                            writer.WriteAttributeString("object", "WScript.Shell");
                            writer.WriteEndElement(); // reference

                            writer.WriteStartElement("reference");
                            writer.WriteAttributeString("object", "Scripting.FileSystemObject");
                            writer.WriteEndElement(); // reference

                            writer.WriteStartElement("script");
                            writer.WriteAttributeString("language", "JScript");
                            var installerArgumentsEsc = string.IsNullOrEmpty(Arguments) ? "" : " " + HttpUtility.JavaScriptStringEncode(Arguments);
                            var argv = Environment.GetCommandLineArgs();
                            var arguments = new StringBuilder();
                            for (long i = 1, n = argv.LongLength; i < n; i++)
                            {
                                if (i > 1) arguments.Append(" ");
                                arguments.Append("\"");
                                arguments.Append(argv[i].Replace("\"", "\"\""));
                                arguments.Append("\"");
                            }
                            var script = new StringBuilder();
                            script.AppendLine("var wsh = WScript.CreateObject(\"WScript.Shell\");");
                            script.AppendLine("wsh.Run(\"\\\"" + HttpUtility.JavaScriptStringEncode(installerFilename.Replace("\"", "\"\"")) + "\\\"" + installerArgumentsEsc + "\", 0, true);");
                            script.AppendLine("var fso = WScript.CreateObject(\"Scripting.FileSystemObject\");");
                            script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(installerFilename) + "\", true); } catch (err) {}");
                            script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(updaterFilename) + "\", true); } catch (err) {}");
                            script.AppendLine("try { fso.DeleteFolder(\"" + HttpUtility.JavaScriptStringEncode(workingFolder.TrimEnd(Path.DirectorySeparatorChar)) + "\", true); } catch (err) {}");
                            writer.WriteCData(script.ToString());
                            writer.WriteEndElement(); // script

                            writer.WriteEndElement(); // job
                            writer.WriteEndElement(); // package
                            writer.WriteEndDoreplacedent();
                            writer.Flush();

                            // Prepare WSF launch parameters.
                            Trace.TraceInformation("Launching update script file {0}...", updaterFilename);
                            var process = new Process();
                            process.StartInfo.FileName = "wscript.exe";
                            process.StartInfo.Arguments = "\"" + updaterFilename + "\"";
                            process.StartInfo.WorkingDirectory = workingFolder;

                            // Close WSF and installer files as late as possible to narrow the attack window.
                            // If Windows supported executing files that are locked for writing, we could leave those files open.
                            updaterFile.Close();
                            installerFile.Close();
                            process.Start();
                        }
                        catch
                        {
                            // Close WSF file.
                            updaterFile.Close();

                            // Delete WSF file. If possible.
                            Trace.TraceInformation("Deleting file {0}...", updaterFilename);
                            try { File.Delete(updaterFilename); }
                            catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", updaterFilename, ex2.ToString()); }

                            throw;
                        }
                    }
                    catch
                    {
                        // Close installer file.
                        installerFile.Close();

                        // Delete installer file. If possible.
                        Trace.TraceInformation("Deleting file {0}...", installerFilename);
                        try { File.Delete(installerFilename); }
                        catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }

                        throw;
                    }
                }
                catch
                {
                    // Delete working folder. If possible.
                    try { Directory.Delete(workingFolder); }
                    catch (Exception ex2) { Trace.TraceWarning("Deleting {0} folder failed: {1}", workingFolder, ex2.ToString()); }

                    throw;
                }
            };

            // Self-update progress.
            selfUpdate.ProgressChanged += (object sender, ProgressChangedEventArgs e) =>
            {
                Progress.Value = e.ProgressPercentage;
            };

            // Self-update complereplacedion.
            selfUpdate.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
            {
                if (e.Error == null)
                {
                    // Self-updating successfuly launched. Quit to release open files.
                    Wizard.OnQuitApplication(this);
                }
                else
                    Wizard.Error = e.Error;

                // Self-dispose.
                (sender as BackgroundWorker)?.Dispose();
            };

            selfUpdate.RunWorkerAsync();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : AVPolyakov

[STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var args = Environment.GetCommandLineArgs();
            var controller = new SingleInstanceController();
            controller.Run(args);
        }

19 View Source File : MainViewModel.cs
License : GNU General Public License v3.0
Project Creator : AdamMYoung

private void LoadGroup()
        {
#if (DEBUG)
            Group = FileManager.LoadGroups().First();
        #endif

#if (!DEBUG)
            var args = Environment.GetCommandLineArgs();
            var dictionary = new Dictionary<string, string>();

            for (var index = 1; index < args.Length; index += 2) dictionary.Add(args[index], args[index + 1]);

            if (dictionary.TryGetValue("/GroupId", out var value))
                Group = FileManager.LoadGroups().FirstOrDefault(x => x.Uid == value);
#endif
        }

19 View Source File : WorkerHostBuilderExtensions.cs
License : MIT License
Project Creator : Azure

public static IHostBuilder ConfigureFunctionsWorkerDefaults(this IHostBuilder builder, Action<HostBuilderContext, IFunctionsWorkerApplicationBuilder> configure, Action<WorkerOptions> configureOptions)
        {
            builder
                .ConfigureHostConfiguration(config =>
                {
                    // Add AZURE_FUNCTIONS_ prefixed environment variables
                    config.AddEnvironmentVariables("AZURE_FUNCTIONS_");
                })
                .ConfigureAppConfiguration(configBuilder =>
                {
                    configBuilder.AddEnvironmentVariables();

                    var cmdLine = Environment.GetCommandLineArgs();
                    RegisterCommandLine(configBuilder, cmdLine);
                })
                .ConfigureServices((context, services) =>
                {
                    IFunctionsWorkerApplicationBuilder appBuilder = services.AddFunctionsWorkerDefaults(configureOptions);

                    // Call the provided configuration prior to adding default middleware
                    configure(context, appBuilder);

                    // Add default middleware
                    appBuilder.UseDefaultWorkerMiddleware();
                });

            return builder;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Analogy-LogViewer

[STAThread]
        static void Main()
        {
            AppDomain.CurrentDomain.replacedemblyLoad += CurrentDomain_replacedemblyLoad;
            DevExpress.UserSkins.BonusSkins.Register();
            WindowsFormsSettings.LoadApplicationSettings();
            WindowsFormsSettings.SetDPIAware();
            replacedogyLogManager.Instance.LogInformation($"OS: {Environment.OSVersion.Version}", nameof(Program));
            if (Environment.OSVersion.Version.Major >= 10)
            {
                WindowsFormsSettings.ForceDirectXPaint();
            }
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            replacedemblyLocation = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
            AppDomain.CurrentDomain.replacedemblyResolve += CurrentDomain_replacedemblyResolve;
            WindowsFormsSettings.DefaultFont = Settings.FontSettings.UIFont;
            WindowsFormsSettings.DefaultMenuFont = Settings.FontSettings.MenuFont;
            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            if (Settings.EnableFirstChanceException)
            {
                AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
            }
            Settings.OnEnableFirstChanceExceptionChanged += (s, e) =>
            {
                if (e)
                {
                    AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
                }
                else
                {
                    AppDomain.CurrentDomain.FirstChanceException -= CurrentDomain_FirstChanceException;
                }
            };
            Application.SetCompatibleTextRenderingDefault(false);
            Application.EnableVisualStyles();
#if NETCOREAPP3_1 || NET
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
#endif
            Settings.IncreaseNumberOfLaunches();
            if (!string.IsNullOrEmpty(Settings.ApplicationSkinName))
            {
                if (!string.IsNullOrEmpty(Settings.ApplicationSvgPaletteName))
                {
                    UserLookAndFeel.Default.SetSkinStyle(Settings.ApplicationSkinName, Settings.ApplicationSvgPaletteName);
                }
                else
                {
                    UserLookAndFeel.Default.SetSkinStyle(Settings.ApplicationSkinName);
                }

                UserLookAndFeel.Default.Style = Settings.ApplicationStyle;
            }

            UserLookAndFeel.Default.StyleChanged += (s, e) =>
            {
                UserLookAndFeel laf = (UserLookAndFeel)s;
                Settings.ApplicationSkinName = laf.ActiveSkinName;
                Settings.ApplicationStyle = laf.Style;
                Settings.ApplicationSvgPaletteName = laf.ActiveSvgPaletteName;

            };

            if (UserSettingsManager.UserSettings.SingleInstance &&
                Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
            {

                if (Environment.GetCommandLineArgs().Length == 2)
                {
                    var otherreplacedogy = GetAlreadyRunningInstance();
                    if (otherreplacedogy != null)
                    {
                        SendDataMessage(otherreplacedogy, Environment.GetCommandLineArgs()[1]);
                    }
                }
                else
                {
                    XtraMessageBox.Show("Single instance is on. Exiting this instance", "replacedogy");
                }

                return;
            }

            if (Settings.IsFirstRun)
            {
               //FirstTimeRunForm f = new FirstTimeRunForm();
               //f.ShowDialog();
            }
            if (Settings.MainFormType == MainFormType.RibbonForm)
            {
                Application.Run(new MainForm());
            }
            else
            {
                Application.Run(new FluentDesignMainForm());
            }

        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : beetlex-io

static void Main(string[] args)
        {
            string[] obj = Environment.GetCommandLineArgs();
            var builder = new HostBuilder()
             .ConfigureServices((hostContext, services) =>
             {
                 services
                 .UseBeetlexHttp(o =>
                 {
                     o.Port = 80;
                     o.LogToConsole = true;
                     o.LogLevel = BeetleX.EventArgs.LogType.Info;
                     o.SetDebug();
                 },
                 HttpServer =>
                 {

                 },
                 typeof(Program).replacedembly, typeof(BeetleX.FastHttpApi.Admin._Admin).replacedembly);
             });
            builder.Build().Run();
        }

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

private static void checkArgs()
        {
            String args = "";
            try
            {
                args = Environment.GetCommandLineArgs()[1];
            }
            catch (Exception) { }

            switch (args)
            {
                case "on":
                    createRegistryKey();
                    break;
                case "off":
                    deleteRegistryKey();
                    break;
                default:
                    luanchSteamTwo();
                    break;
            }
        }

19 View Source File : SelfDebugger.cs
License : Apache License 2.0
Project Creator : bezzad

public static void DebugSelf(int ppid)
        {
            Console.WriteLine("Debugging {0}", ppid);
            var self = Process.GetCurrentProcess();
            // Child process?
            if (ppid != 0)
            {
                var pdbg = Process.GetProcessById(ppid);
                new Thread(KillOnExit) { IsBackground = true, Name = "KillOnExit" }.Start(pdbg);
                //Wait for our parent to debug us
                WaitForDebugger();
                //Start debugging our parent process
                DebuggerThread(ppid);
                //Now is a good time to die.
                Environment.Exit(1);
            }
            else // else we are the Parent process...
            {
                var procName = Environment.GetCommandLineArgs()[0];
                procName = procName.Replace(".dll", ".exe");
                var psi = new ProcessStartInfo(procName, self.Id.ToString())
                {
                    UseShellExecute = false,
                    CreateNoWindow = false,
                    ErrorDialog = false,
                    //WindowStyle = ProcessWindowStyle.Hidden
                };
                // Start the child process
                var pdbg = Process.Start(psi);
                if (pdbg == null)
                    throw new ApplicationException("Unable to debug");
                // Monitor the child process
                new Thread(KillOnExit) { IsBackground = true, Name = "KillOnExit" }.Start(pdbg);
                // Debug the child process
                new Thread(DebuggerThread) { IsBackground = true, Name = "DebuggerThread" }.Start(pdbg.Id);
                // Wait for the child to debug us
                WaitForDebugger();
            }
        }

19 View Source File : FileObserver.cs
License : MIT License
Project Creator : AndreiMisiukevich

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        private static void Run()
        {
            var addresses = NetworkInterface.GetAllNetworkInterfaces()
                .SelectMany(x => x.GetIPProperties().UnicastAddresses)
                .Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork)
                .Select(x => x.Address.MapToIPv4())
                .Where(x => x.ToString() != "127.0.0.1")
                .ToArray();

            var ip = addresses.FirstOrDefault()?.ToString() ?? "127.0.0.1";

            var args = Environment.GetCommandLineArgs();
            var path = RetrieveCommandLineArgument("p=", Environment.CurrentDirectory, args);
            var url = RetrieveCommandLineArgument("u=", $"http://{ip}:8000", args);
            var autoDiscoveryPort = RetrieveCommandLineArgument("a=", "15000", args);

            try
            {
                Directory.GetDirectories(path);
            }
            catch
            {
                Console.WriteLine("MAKE SURE YOU PreplacedED RIGHT PATH TO PROJECT DIRECTORY AS 'P={PATH}' ARGUMENT.");
                Console.ReadKey();
                return;
            }

            foreach (var addr in url.Split(new char[] { ',', ';' }))
            {
                if (!Uri.IsWellFormedUriString(addr, UriKind.Absolute))
                {
                    Console.WriteLine("MAKE SURE YOU PreplacedED RIGHT DEVICE URL AS 'U={DEVICE_URL}' OR AS 'U={DEVICE_URL,DEVICE_URL2,...}' ARGUMENT.");
                    Console.ReadKey();
                    return;
                }

                _addresses.Add(addr);
            }

            UdpReceiver receiver = null;
            try
            {
                receiver = new UdpReceiver(int.Parse(autoDiscoveryPort));
                receiver.Received += (addressMsg) =>
                {
                    //TODO: pick needed address
                    var address = addressMsg.Split(';').FirstOrDefault();
                    if (address != null)
                    {
                        if (!_addresses.Contains(address))
                        {
                            Console.WriteLine($"ADDRESS IS DETECTED: {address}");
                            _addresses.Add(address);
                        }
                    }
                };
                receiver.StartAsync();
            }
            catch
            {
                Console.WriteLine("MAKE SURE YOU PreplacedED RIGHT AUTO DISCOVERY RECEIVER PORT AS 'A={PORT}' ARGUMENT.");
                Console.ReadKey();
                return;
            }

            Console.WriteLine($"\n\n> HOTRELOADER STARTED AT {DateTime.Now}");
            Console.WriteLine($"\n> PATH: {path}");
            Console.WriteLine($"\n> AUTO DISCOVERY PORT: {autoDiscoveryPort}");

            foreach (var addr in _addresses)
            {
                Console.WriteLine($"\n> URL: {addr}\n");
            }


            _client = new HttpClient();

            foreach (var fileExtension in _supportedFileExtensions)
            {
                var observer = new FileSystemWatcher
                {
                    Path = path,
                    NotifyFilter = NotifyFilters.LastWrite |
                        NotifyFilters.Attributes |
                        NotifyFilters.Size |
                        NotifyFilters.CreationTime |
                        NotifyFilters.FileName,
                    Filter = $"*{fileExtension}",
                    EnableRaisingEvents = true,
                    IncludeSubdirectories = true
                };

                observer.Changed += OnFileChanged;
                observer.Created += OnFileChanged;
                observer.Renamed += OnFileChanged;
            }

            do
            {
                Console.WriteLine("\nPRESS \'ESC\' TO STOP.");
            } while (Console.ReadKey().Key != ConsoleKey.Escape);

            receiver.Stop();
        }

19 View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

private void OnLoaded(object sender, RoutedEventArgs e)
        {
            string indexPath;
            if (Environment.GetCommandLineArgs().Length > 1 && Path.GetFileName(Environment.GetCommandLineArgs()[1]) == "_.index.bin")
                indexPath = Environment.GetCommandLineArgs()[1];
            else
            {
                var ofd = new OpenFileDialog
                {
                    DefaultExt = "bin",
                    FileName = "_.index.bin",
                    Filter = "GGG Bundle index|_.index.bin"
                };
                if (ofd.ShowDialog() == true)
                    indexPath = ofd.FileName;
                else
                {
                    Close();
                    return;
                }
            }
            if (Path.GetFileName(indexPath) != "_.index.bin")
            {
                MessageBox.Show("You must select _.index.bin!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                Close();
                return;
            }
            Environment.CurrentDirectory = Path.GetDirectoryName(indexPath);
            ic = new IndexContainer("_.index.bin");
            UpdateBundleList();
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

private void initVariables()
        {
            LaunchedViaStartup = Environment.GetCommandLineArgs() != null && Environment.GetCommandLineArgs().Any(arg => arg.Equals("startup", StringComparison.CurrentCultureIgnoreCase));
            encrypted = SteamTwoProperties.jsonSetting.encryptedSetting;
            currentHandle = this;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 13xforever

static async Task<int> Main(string[] args)
        {
            Log.Info("PS3 Disc Dumper v" + Dumper.Version);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
                try
                {
                    Log.Error("Looks like there's no console present, restarting...");
                    var launchArgs = Environment.GetCommandLineArgs()[0];
                    if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
                    {
                        Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
                        using var currentProcess = Process.GetCurrentProcess();
                        var pid = currentProcess.Id;
                        var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
                        launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
                    }
                    Log.Debug($"Using cmdline '{launchArgs}'");
                    launchArgs = $"-e bash -c {launchArgs}";
                    var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
                    using var proc = Process.Start(startInfo);
                    if (proc.WaitForExit(1_000))
                    {
                        if (proc.ExitCode != 0)
                        {
                            startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
                            using var proc2 = Process.Start(startInfo);
                            if (proc2.WaitForExit(1_000))
                            {
                                if (proc2.ExitCode != 0)
                                {
                                    startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
                                    using var proc3 = Process.Start(startInfo);
                                    if (proc3.WaitForExit(1_000))
                                    {
                                        if (proc3.ExitCode != 0)
                                        {
                                            startInfo = new ProcessStartInfo("konsole", launchArgs);
                                            using var _ = Process.Start(startInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return -2;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    return -3;
                }
            var lastDiscId = "";
start:
            const string replacedleBase = "PS3 Disc Dumper";
            var replacedle = replacedleBase;
            Console.replacedle = replacedle;
            var output = ".";
            var inDir = "";
            var showHelp = false;
            var options = new OptionSet
            {
                {
                    "i|input=", "Path to the root of blu-ray disc mount", v =>
                    {
                        if (v is string ind)
                            inDir = ind;
                    }
                },
                {
                    "o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
                    {
                        if (v is string outd)
                            output = outd;
                    }
                },
                {
                    "?|h|help", "Show help", v =>
                    {
                        if (v != null)
                            showHelp = true;
                    },
                    true
                },
            };
            try
            {
                var unknownParams = options.Parse(args);
                if (unknownParams.Count > 0)
                {
                    Log.Warn("Unknown parameters: ");
                    foreach (var p in unknownParams)
                        Log.Warn("\t" + p);
                    showHelp = true;
                }
                if (showHelp)
                {
                    ShowHelp(options);
                    return 0;
                }

                var dumper = new Dumper(ApiConfig.Cts);
                dumper.DetectDisc(inDir);
                await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
                if (string.IsNullOrEmpty(dumper.OutputDir))
                {
                    Log.Info("No compatible disc was found, exiting");
                    return 2;
                }
                if (lastDiscId == dumper.ProductCode)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
                    Console.ResetColor();
                    var confirmKey = Console.ReadKey(true);
                    switch (confirmKey.Key)
                    {
                        case ConsoleKey.Y:
                            break;
                        default:
                            throw new OperationCanceledException("Aborting re-dump of the same disc");
                    }
                }
                lastDiscId = dumper.ProductCode;

                replacedle += " - " + dumper.replacedle;
                var monitor = new Thread(() =>
                {
                    try
                    {
                        do
                        {
                            if (dumper.CurrentSector > 0)
                                Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
                            Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
                        } while (!ApiConfig.Cts.Token.IsCancellationRequested);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    Console.replacedle = replacedle;
                });
                monitor.Start();

                await dumper.DumpAsync(output).ConfigureAwait(false);

                ApiConfig.Cts.Cancel(false);
                monitor.Join(100);

                if (dumper.BrokenFiles.Count > 0)
                {
                    Log.Fatal("Dump is not valid");
                    foreach (var file in dumper.BrokenFiles)
                        Log.Error($"{file.error}: {file.filename}");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Dump is valid");
                    Console.ResetColor();
                }
            }
            catch (OptionException)
            {
                ShowHelp(options);
                return 1;
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
            }
            Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.X:
                    return 0;
                default:
                    goto start;
            }
        }

19 View Source File : ExternalCommunicator.cs
License : Apache License 2.0
Project Creator : A7ocin

private void ReadArgs()
    {
        string[] args = System.Environment.GetCommandLineArgs();
        string inputPort = "";
        for (int i = 0; i < args.Length; i++)
        {
            if (args[i] == "--port")
            {
                inputPort = args[i + 1];
            }
        }

        comPort = int.Parse(inputPort);
    }

19 View Source File : Util.cs
License : MIT License
Project Creator : ajayyy

public static float GetCommandLineArgValue( string argumentName, float flDefaultValue )
		{
			string[] args = System.Environment.GetCommandLineArgs();
			for ( int i = 0; i < args.Length; i++ )
			{
				if ( args[i].Equals( argumentName ) )
				{
					if ( i == ( args.Length - 1 ) ) // Last arg, return default
					{
						return flDefaultValue;
					}

					return (float)Double.Parse( args[i + 1] );
				}
			}

			return flDefaultValue;
		}

19 View Source File : Utility.cs
License : MIT License
Project Creator : Ashesh3

public static T GetStartOption<T>(string pattern, Func<Match, T> formatFunc, T defaultValue = default(T))
        {
            if (formatFunc == null)
                return defaultValue;

            var args = Environment.GetCommandLineArgs();
            foreach (var arg in args)
            {
                var regex = Regex.Match(arg, pattern, RegexOptions.IgnoreCase);
                if (!regex.Success)
                    continue;

                return formatFunc.Invoke(regex);
            }

            return defaultValue;
        }

See More Examples