コード例 #1
0
ファイル: Program.cs プロジェクト: semenow94/HomeWorksCS1
        static void Main()
        {
            Console.WindowWidth = 70;
            Console.SetBufferSize(Console.WindowWidth, Console.WindowHeight);
            int i;

            do
            {
                i = Menu();
                Console.WriteLine();
                Console.WriteLine("****************************************************************");
                switch (i)
                {
                case 1:
                    Tasks.Task1();
                    break;

                case 2:
                    Tasks.Task2();
                    break;

                case 3:
                    Tasks.Task3();
                    break;

                case 0:
                    Console.WriteLine("GoodBye!");
                    break;
                }
                Console.WriteLine("****************************************************************");
                Console.WriteLine();
            } while (i != 0);
            ConsoleHelp.Pause();
        }
コード例 #2
0
ファイル: PowerShell.cs プロジェクト: tyronebj/mpv.net
        public void Error_DataReady(object sender, EventArgs e)
        {
            var output = sender as PipelineReader <Object>;

            while (output.Count > 0)
            {
                ConsoleHelp.WriteError(output.Read(), Module);
            }
        }
コード例 #3
0
        public static void marge(string[] args)
        {
            #region (x.1) get arg
            string input = ConsoleHelp.GetArg(args, "-i") ?? ConsoleHelp.GetArg(args, "--input");
            if (string.IsNullOrEmpty(input))
            {
                ConsoleHelp.Log("请指定要合并的文件(夹)");
                return;
            }

            string output = ConsoleHelp.GetArg(args, "-o") ?? ConsoleHelp.GetArg(args, "--output");
            if (string.IsNullOrEmpty(output))
            {
                ConsoleHelp.Log("请指定输出文件");
                return;
            }
            #endregion

            ConsoleHelp.Log("开始合并");
            ConsoleHelp.Log("待合并的文件(夹):" + input);
            ConsoleHelp.Log("输出文件:" + output);


            #region (x.2)获取 要合并的文件
            string[] inFiles;
            if (input.IndexOf('*') > 0)
            {
                inFiles = new DirectoryInfo(Path.GetDirectoryName(input)).GetFiles(Path.GetFileName(input)).OrderBy(m => m.Name).Select(m => m.FullName).ToArray();
            }
            else
            {
                inFiles = new DirectoryInfo(input).GetFiles().OrderBy(m => m.Name).Select(m => m.FullName).ToArray();
            }
            var sum = inFiles.Count();
            ConsoleHelp.Log("要合并的文件总数:" + sum);

            #endregion


            #region (x.3)合并文件
            File.Delete(output);
            using (var sw = new FileStream(output, FileMode.CreateNew))
            {
                int finished = 0;
                foreach (var inFile in inFiles)
                {
                    ConsoleHelp.Log($"[{ ++finished }/{sum}]合并文件:" + inFile);
                    using (var reader = new FileStream(inFile, FileMode.Open))
                    {
                        reader.CopyTo(sw);
                    }
                }
            }
            #endregion

            ConsoleHelp.Log("文件合并成功!!!");
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: semenow94/HomeWorksCS1
        static void Main()
        {
            double imt, height, weight, height_m;

            Console.Write("Какой у вас рост в см? ");
            height = Convert.ToDouble(Console.ReadLine());
            Console.Write("Какой у вас вес? ");
            weight   = Convert.ToDouble(Console.ReadLine());
            height_m = height / 100;
            imt      = weight / (height_m * height_m);
            Console.WriteLine("При росте {0}см и весе {1}кг, ваш ИМТ = {2:F}", height, weight, imt);
            ConsoleHelp.Pause();
        }
コード例 #5
0
ファイル: Theme.cs プロジェクト: tyronebj/mpv.net
        public static void Init(string customContent, string defaultContent, string activeTheme)
        {
            DefaultThemes = Load(defaultContent);
            CustomThemes  = Load(customContent);

            foreach (Theme theme in CustomThemes)
            {
                if (theme.Name == activeTheme)
                {
                    bool isKeyMissing = false;

                    foreach (string key in DefaultThemes[0].Dictionary.Keys)
                    {
                        if (!theme.Dictionary.ContainsKey(key))
                        {
                            isKeyMissing = true;
                            ConsoleHelp.WriteError($"Theme '{activeTheme}' misses '{key}'", "mpv.net");
                            break;
                        }
                    }

                    if (!isKeyMissing)
                    {
                        Current = theme;
                    }

                    break;
                }
            }

            if (Current == null)
            {
                foreach (Theme theme in DefaultThemes)
                {
                    if (theme.Name == activeTheme)
                    {
                        Current = theme;
                    }
                }
            }

            if (Current == null)
            {
                Current = DefaultThemes[0];
            }

            Foreground  = Current.GetBrush("foreground");
            Foreground2 = Current.GetBrush("foreground2");
            Background  = Current.GetBrush("background");
            Heading     = Current.GetBrush("heading");
        }
コード例 #6
0
        public override int Run(string[] remainingArguments)
        {
            string[] args;

            bool isInputRedirected = _redirectionDetector.IsInputRedirected();

            if (!isInputRedirected)
            {
                WritePromptForCommands();
            }

            bool   haveError = false;
            string input     = _inputStream.ReadLine();

            while (!input.Trim().Equals("x"))
            {
                if (input.Trim().Equals("?"))
                {
                    ConsoleHelp.ShowSummaryOfCommands(GetNextCommands(), _outputStream);
                }
                else
                {
                    args = CommandLineParser.Parse(input);

                    var result = ConsoleCommandDispatcher.DispatchCommand(GetNextCommands(), args, _outputStream, true);
                    if (result != 0)
                    {
                        haveError = true;

                        if (isInputRedirected)
                        {
                            return(result);
                        }
                    }
                }

                if (!isInputRedirected)
                {
                    _outputStream.WriteLine();

                    if (!isInputRedirected)
                    {
                        WritePromptForCommands();
                    }
                }

                input = _inputStream.ReadLine();
            }

            return(haveError ? -1 : 0);
        }
コード例 #7
0
        private static int DealWithException(Exception e, TextWriter console, bool skipExeInExpectedUsage, ConsoleCommand selectedCommand, IEnumerable <ConsoleCommand> commands)
        {
            if (selectedCommand != null)
            {
                console.WriteLine();
                console.WriteLine(e.Message);
                ConsoleHelp.ShowCommandHelp(selectedCommand, console, skipExeInExpectedUsage);
            }
            else
            {
                ConsoleHelp.ShowSummaryOfCommands(commands, console);
            }

            return(-1);
        }
コード例 #8
0
        static void Main()
        {
            string name, surname, city;

            name                 = "Дмитрий";
            surname              = "Семенов";
            city                 = "Наро-Фоминск";
            Console.WindowWidth  = 50;
            Console.WindowHeight = 20;
            Console.SetBufferSize(Console.WindowWidth, Console.WindowHeight);
            //Можно было рассчитать и позицию по высоте через массив и выводить пробегая по элементам массива, но мен лень =)
            PrintInCenter(name, 9);
            PrintInCenter(surname, 10);
            PrintInCenter(city, 11);
            ConsoleHelp.Pause();
        }
コード例 #9
0
        static void Main()
        {
            double x1, x2, y1, y2, distance;

            Console.Write("Введите точку x1 ");
            x1 = Convert.ToDouble(Console.ReadLine());
            Console.Write("Введите точку y1 ");
            y1 = Convert.ToDouble(Console.ReadLine());
            Console.Write("Введите точку x2 ");
            x2 = Convert.ToDouble(Console.ReadLine());
            Console.Write("Введите точку y2 ");
            y2       = Convert.ToDouble(Console.ReadLine());
            distance = Distance(x1, y1, x2, y2);
            Console.WriteLine($"Расстояние между точкой [{x1},{y1}] и точкой [{x2},{y2}] = {distance:F2}");
            ConsoleHelp.Pause();
        }
コード例 #10
0
ファイル: Program.cs プロジェクト: semenow94/HomeWorksCS1
        static void Main()
        {
            int a, b, c;

            a = 1;
            b = 2;
            Console.WriteLine($"a={a}, b={b}");
            c = a;
            a = b;
            b = c;
            Console.WriteLine($"После обмена через третью переменную a={a}, b={b}");

            a = 5;
            b = 4;
            Console.WriteLine($"a={a}, b={b}");
            a += b;
            b  = a - b;
            a -= b;
            Console.WriteLine($"После обмена без третьей переменной a={a}, b={b}");
            ConsoleHelp.Pause();
        }
コード例 #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            //var arg = new List<string>() { "help" };
            //args = arg.ToArray();


            //var arg = new List<string>() { "unzip" };
            //arg.AddRange(new[] { "-i", "T:\\temp\\tileset.zip" });
            //arg.AddRange(new[] { "-o", "T:\\temp\\tileset" });
            //args = arg.ToArray();

            //var arg = new List<string>() { "zip" };
            //arg.AddRange(new[] { "-i", "T:\\temp\\tileset" });
            ////arg.AddRange(new[] { "-o", "T:\\temp\\tileset.zip" });
            //args = arg.ToArray();

            Vit.ConsoleUtil.ConsoleHelp.Log("[FileZip] version: " + System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetEntryAssembly().Location).FileVersion);

            ConsoleHelp.Exec(args);
            return;
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: semenow94/HomeWorksCS1
        static void Main()
        {
            string name, surname, str;
            int    age, height, weight;

            Console.Write("Как вас зовут? ");
            name = Console.ReadLine();
            Console.Write("Привет, " + name + ", а твоя фамилия? ");
            surname = Console.ReadLine();
            Console.Write(name + " " + surname + ", сколько тебе лет? ");
            str = Console.ReadLine();
            age = Convert.ToInt32(str);
            Console.Write(name + " " + surname + ", какой у тебя рост? ");
            str    = Console.ReadLine();
            height = Convert.ToInt32(str);
            Console.Write(name + " " + surname + ", какой у тебя вес? ");
            str    = Console.ReadLine();
            weight = Convert.ToInt32(str);
            Console.WriteLine(name + " " + surname + ", ваш возраст - " + age + " , рост - " + height + " , вес - " + weight);
            Console.WriteLine("{0} {1}, ваш возраст - {2} , рост - {3} , вес - {4:F}", name, surname, age, height, weight);
            Console.WriteLine($"{name} {surname}, ваш возраст - {age} , рост - {height} , вес - {weight}");
            ConsoleHelp.Pause();
        }
コード例 #13
0
        public static int DispatchCommand(IEnumerable <ConsoleCommand> commands, string[] arguments, TextWriter consoleOut)
        {
            ConsoleCommand selectedCommand = null;

            TextWriter console = consoleOut;

            try
            {
                List <string> remainingArguments;

                if (commands.Count() == 1)
                {
                    selectedCommand = commands.First();

                    CheckCommandProperty(selectedCommand);

                    if (arguments.Count() > 0 && arguments.First().ToLower() == selectedCommand.Command.ToLower())
                    {
                        remainingArguments = selectedCommand.Options.Parse(arguments.Skip(1));
                    }
                    else
                    {
                        remainingArguments = selectedCommand.Options.Parse(arguments);
                    }
                }
                else
                {
                    if (arguments.Count() < 1)
                    {
                        throw new ConsoleHelpAsException("No arguments specified.");
                    }

                    foreach (var possibleCommand in commands)
                    {
                        CheckCommandProperty(possibleCommand);

                        if (arguments.First().ToLower() == possibleCommand.Command.ToLower())
                        {
                            selectedCommand = possibleCommand;

                            break;
                        }
                    }

                    if (selectedCommand == null)
                    {
                        throw new ConsoleHelpAsException("Command name not recognized.");
                    }

                    remainingArguments = selectedCommand.Options.Parse(arguments.Skip(1));
                }

                CheckRequiredArguments(selectedCommand);

                CheckRemainingArguments(remainingArguments, selectedCommand.RemainingArgumentsCount);

                ConsoleHelp.ShowParsedCommand(selectedCommand, console);

                return(selectedCommand.Run(remainingArguments.ToArray()));
            }
            catch (Exception e)
            {
                if (!ConsoleHelpAsException.WriterErrorMessage(e, console))
                {
                    throw;
                }

                console.WriteLine();

                if (selectedCommand != null)
                {
                    if (e is ConsoleHelpAsException || e is NDesk.Options.OptionException)
                    {
                        ConsoleHelp.ShowCommandHelp(selectedCommand, console);
                    }
                }
                else
                {
                    ConsoleHelp.ShowSummaryOfCommands(commands, console);
                }

                return(-1);
            }
        }
コード例 #14
0
        public static int Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;

            string inputFile   = null;
            string outputFile  = null;
            string scriptFile  = null;
            bool   showHelp    = false;
            bool   quitOnError = true;

            var p = new OptionSet
            {
                { "i|input-file=", "read configuration from {FILE}", value => inputFile = value },
                { "o|output-file=", "write results to {FILE}", value => outputFile = value },
                { "s|script-file=", "runs commands from {FILE}", value => scriptFile = value },
                { "c|continue", "continues when an error occurs while loading the configuration", value => quitOnError = value == null },
                { "h|help", "show this help message and exit", value => showHelp = value != null }
            };

            try
            {
                p.Parse(args);
            }
            catch (OptionException)
            {
                ShowHelp(p);
                return(-1);
            }

            if (showHelp || string.IsNullOrEmpty(inputFile))
            {
                ShowHelp(p);
                return(-1);
            }

            HCContext  context;
            TextWriter output = null;

            try
            {
                if (!string.IsNullOrEmpty(outputFile))
                {
                    output = new StreamWriter(outputFile);
                }

                Console.Write("Reading configuration file \"{0}\"... ", Path.GetFileName(inputFile));
                Language language = XmlLanguageLoader.Load(inputFile, quitOnError ? (Action <Exception, string>)null : (ex, id) => { });
                Console.WriteLine("done.");

                context = new HCContext(language, output ?? Console.Out);
                Console.Write("Compiling rules... ");
                context.Compile();
                Console.WriteLine("done.");
                Console.WriteLine("{0} loaded.", language.Name);
                Console.WriteLine();
            }
            catch (IOException ioe)
            {
                Console.WriteLine();
                Console.WriteLine("IO Error: " + ioe.Message);
                if (output != null)
                {
                    output.Close();
                }
                return(-1);
            }
            catch (Exception e)
            {
                Console.WriteLine();
                Console.WriteLine("Load Error: " + e.Message);
                if (output != null)
                {
                    output.Close();
                }
                return(-1);
            }

            ConsoleCommand[] commands = { new ParseCommand(context), new TracingCommand(context), new TestCommand(context), new StatsCommand(context) };

            string input;

            if (!string.IsNullOrEmpty(scriptFile))
            {
                using (var scriptReader = new StreamReader(scriptFile))
                {
                    input = scriptReader.ReadLine();
                    while (input != null)
                    {
                        if (!input.Trim().StartsWith("#") && input.Trim() != "")
                        {
                            string[] cmdArgs = CommandLineParser.Parse(input);
                            ConsoleCommandDispatcher.DispatchCommand(commands, cmdArgs, context.Out);
                        }
                        input = scriptReader.ReadLine();
                    }
                }
            }
            else
            {
                Console.Write("> ");
                input = Console.ReadLine();
                while (input != null && input.Trim() != "exit")
                {
                    if (input.Trim().IsOneOf("?", "help"))
                    {
                        ConsoleHelp.ShowSummaryOfCommands(commands, Console.Out);
                    }
                    else
                    {
                        string[] cmdArgs = CommandLineParser.Parse(input);
                        ConsoleCommandDispatcher.DispatchCommand(commands, cmdArgs, context.Out);
                    }
                    Console.Write("> ");
                    input = Console.ReadLine();
                }
            }

            if (output != null)
            {
                output.Close();
            }

            return(0);
        }
コード例 #15
0
        public static void unzip(string[] args)
        {
            #region (x.1) get arg
            string input = ConsoleHelp.GetArg(args, "-i") ?? ConsoleHelp.GetArg(args, "--input");
            if (string.IsNullOrEmpty(input))
            {
                ConsoleHelp.Log("请指定待解压文件");
                return;
            }

            string output = ConsoleHelp.GetArg(args, "-o") ?? ConsoleHelp.GetArg(args, "--output");
            if (string.IsNullOrEmpty(output))
            {
                output = Path.GetDirectoryName(input);
            }
            Directory.CreateDirectory(output);

            float? progress    = null;
            string strProgress = ConsoleHelp.GetArg(args, "-p") ?? ConsoleHelp.GetArg(args, "--progress");
            if (strProgress == "")
            {
                progress = 0.1f;
            }
            else if (strProgress != null)
            {
                if (float.TryParse(strProgress, out var pro) && pro > 0 & pro <= 1)
                {
                    progress = pro;
                }
            }

            bool printFile = !(ConsoleHelp.GetArg(args, "-f") == null && ConsoleHelp.GetArg(args, "--file") == null);

            bool printDirectory = !(ConsoleHelp.GetArg(args, "-d") == null && ConsoleHelp.GetArg(args, "--dir") == null);
            #endregion

            bool inputFileIsTemp = false;


            try
            {
                #region (x.2)若为压缩分卷文件则合并到临时文件
                {
                    var extension = Path.GetExtension(input).TrimStart('.');
                    if (int.TryParse(extension, out _))
                    {
                        var fileSearch = Path.Combine(Path.GetDirectoryName(input), Path.GetFileNameWithoutExtension(input) + ".*");

                        input = Path.Combine(Path.GetDirectoryName(input), "tmp_" + Path.GetFileNameWithoutExtension(input) + ".tmp");

                        inputFileIsTemp = true;
                        var cmd = new List <string>()
                        {
                            "marge"
                        };
                        cmd.AddRange(new[] { "-i", fileSearch });
                        cmd.AddRange(new[] { "-o", input });
                        Marge.marge(cmd.ToArray());
                    }
                }
                #endregion



                #region (x.3) 开始解压

                ConsoleHelp.Log("开始解压");
                ConsoleHelp.Log("待解压文件:" + input);
                ConsoleHelp.Log("输出目录:" + output);


                var unpack = new App.Logical.FileUnpack
                {
                    inputPath  = input,
                    outputPath = output
                };


                if (printFile)
                {
                    unpack.OnFile = (int sumCount, int curCount, string fileName) => ConsoleHelp.Log($"[{ curCount }/{sumCount} f]  " + fileName);
                }

                if (printDirectory)
                {
                    unpack.OnDir = (int sumCount, int curCount, string fileName) => ConsoleHelp.Log($"[{ curCount }/{sumCount} d]  " + fileName);
                }

                if (progress != null)
                {
                    unpack.progressStep = progress.Value;
                    unpack.OnProgress   = (float pro, int sumCount, int curCount) => { ConsoleHelp.Log($"[{curCount}/{sumCount}] 已完成 { pro * 100 } %"); };
                }

                unpack.Unpack();


                ConsoleHelp.Log("文件解压成功!!!");

                #endregion
            }
            finally
            {
                if (inputFileIsTemp)
                {
                    ConsoleHelp.Log("删除临时文件:" + input);
                    File.Delete(input);
                }
            }
        }
コード例 #16
0
ファイル: PowerShell.cs プロジェクト: tyronebj/mpv.net
        void Output_DataAdded(object sender, DataAddedEventArgs e)
        {
            var output = sender as PSDataCollection <PSObject>;

            ConsoleHelp.Write(output[e.Index], Module);
        }
コード例 #17
0
ファイル: PowerShell.cs プロジェクト: tyronebj/mpv.net
        void Error_DataAdded(object sender, DataAddedEventArgs e)
        {
            var error = sender as PSDataCollection <ErrorRecord>;

            ConsoleHelp.WriteError(error[e.Index], Module);
        }
コード例 #18
0
        private static (ConsoleCommand, string[], int?) GetSelectedCommand(IEnumerable <ConsoleCommand> commands, string[] arguments, TextWriter consoleOut, bool skipExeInExpectedUsage = false)
        {
            ConsoleCommand selectedCommand = null;
            List <string>  remainingArguments;

            TextWriter console = consoleOut;

            foreach (var command in commands)
            {
                ValidateConsoleCommand(command);
            }

            try
            {
                if (commands.Count() == 1)
                {
                    selectedCommand = commands.First();

                    if (arguments.Count() > 0 && CommandMatchesArgument(selectedCommand, arguments.First()))
                    {
                        remainingArguments = selectedCommand.GetActualOptions().Parse(arguments.Skip(1));
                    }
                    else
                    {
                        remainingArguments = selectedCommand.GetActualOptions().Parse(arguments);
                    }
                }
                else
                {
                    if (arguments.Count() < 1)
                    {
                        throw new ConsoleHelpAsException("No arguments specified.");
                    }

                    if (arguments[0].Equals("help", StringComparison.InvariantCultureIgnoreCase))
                    {
                        selectedCommand = GetMatchingCommand(commands, arguments.Skip(1).FirstOrDefault());

                        if (selectedCommand == null)
                        {
                            ConsoleHelp.ShowSummaryOfCommands(commands, console);
                        }
                        else
                        {
                            ConsoleHelp.ShowCommandHelp(selectedCommand, console, skipExeInExpectedUsage);
                        }

                        return(null, null, -1);
                    }

                    selectedCommand = GetMatchingCommand(commands, arguments.First());

                    if (selectedCommand == null)
                    {
                        throw new ConsoleHelpAsException("Command name not recognized.");
                    }

                    remainingArguments = selectedCommand.GetActualOptions().Parse(arguments.Skip(1));
                }

                selectedCommand.CheckRequiredArguments();

                CheckRemainingArguments(remainingArguments, selectedCommand.RemainingArgumentsCountMin, selectedCommand.RemainingArgumentsCountMax);

                var preResult = selectedCommand.OverrideAfterHandlingArgumentsBeforeRun(remainingArguments.ToArray());

                if (preResult.HasValue)
                {
                    return(null, null, preResult);
                }

                ConsoleHelp.ShowParsedCommand(selectedCommand, console);
                return(selectedCommand, remainingArguments.ToArray(), null);
            }
            catch (ConsoleHelpAsException e)
            {
                return(null, null, DealWithException(e, console, skipExeInExpectedUsage, selectedCommand, commands));
            }
            catch (Mono.Options.OptionException e)
            {
                return(null, null, DealWithException(e, console, skipExeInExpectedUsage, selectedCommand, commands));
            }
        }
コード例 #19
0
        public static int DispatchCommand(IEnumerable <ConsoleCommand> commands, string[] arguments, TextWriter consoleOut, bool skipExeInExpectedUsage = false)
        {
            ConsoleCommand selectedCommand = null;

            TextWriter console = consoleOut;

            IEnumerable <ConsoleCommand> consoleCommands = commands as ConsoleCommand[] ?? commands.ToArray();

            foreach (var command in consoleCommands)
            {
                ValidateConsoleCommand(command);
            }

            try
            {
                List <string> remainingArguments;

                if (consoleCommands.Count() == 1)
                {
                    selectedCommand = consoleCommands.First();

                    if (arguments.Any() && (arguments.First().ToLower() == selectedCommand.Command.ToLower()))
                    {
                        remainingArguments = selectedCommand.GetActualOptions().Parse(arguments.Skip(1));
                    }
                    else
                    {
                        remainingArguments = selectedCommand.GetActualOptions().Parse(arguments);
                    }
                }
                else
                {
                    if (!arguments.Any())
                    {
                        throw new ConsoleHelpAsException("No arguments specified.");
                    }

                    if (arguments[0].Equals("help", StringComparison.InvariantCultureIgnoreCase))
                    {
                        selectedCommand = GetMatchingCommand(consoleCommands, arguments.Skip(1).FirstOrDefault());

                        if (selectedCommand == null)
                        {
                            ConsoleHelp.ShowSummaryOfCommands(consoleCommands, console);
                        }
                        else
                        {
                            ConsoleHelp.ShowCommandHelp(selectedCommand, console, skipExeInExpectedUsage);
                        }

                        return(-1);
                    }

                    selectedCommand = GetMatchingCommand(consoleCommands, arguments.First());

                    if (selectedCommand == null)
                    {
                        throw new ConsoleHelpAsException("Command name not recognized.");
                    }

                    remainingArguments = selectedCommand.GetActualOptions().Parse(arguments.Skip(1));
                }

                selectedCommand.CheckRequiredArguments();

                CheckRemainingArguments(remainingArguments, selectedCommand.RemainingArgumentsCount);

                var preResult = selectedCommand.OverrideAfterHandlingArgumentsBeforeRun(remainingArguments.ToArray());

                if (preResult.HasValue)
                {
                    return(preResult.Value);
                }

                ConsoleHelp.ShowParsedCommand(selectedCommand, console);

                return(selectedCommand.Run(remainingArguments.ToArray()));
            }
            catch (ConsoleHelpAsException e)
            {
                return(DealWithException(e, console, skipExeInExpectedUsage, selectedCommand, consoleCommands));
            }
            catch (NDesk.Options.OptionException e)
            {
                return(DealWithException(e, console, skipExeInExpectedUsage, selectedCommand, consoleCommands));
            }
        }
コード例 #20
0
        public static void zip(string[] args)
        {
            #region (x.1) get arg
            string input = ConsoleHelp.GetArg(args, "-i") ?? ConsoleHelp.GetArg(args, "--input");
            if (string.IsNullOrEmpty(input))
            {
                ConsoleHelp.Log("请指定待压缩文件(夹)");
                return;
            }

            string output = ConsoleHelp.GetArg(args, "-o") ?? ConsoleHelp.GetArg(args, "--output");
            if (string.IsNullOrEmpty(output))
            {
                output = Path.GetDirectoryName(input) + ".zip";
            }
            Directory.CreateDirectory(Path.GetDirectoryName(output));

            float? progress    = null;
            string strProgress = ConsoleHelp.GetArg(args, "-p") ?? ConsoleHelp.GetArg(args, "--progress");
            if (strProgress == "")
            {
                progress = 0.1f;
            }
            else if (strProgress != null)
            {
                if (float.TryParse(strProgress, out var pro) && pro > 0 & pro <= 1)
                {
                    progress = pro;
                }
            }

            bool printFile = !(ConsoleHelp.GetArg(args, "-f") == null && ConsoleHelp.GetArg(args, "--file") == null);
            #endregion


            #region (x.2) 开始解压

            ConsoleHelp.Log("开始压缩");
            ConsoleHelp.Log("待压缩文件(夹):" + input);
            ConsoleHelp.Log("压缩后文件:" + output);


            var pack = new App.Logical.FilePack
            {
                inputPath  = input,
                outputPath = output
            };


            if (printFile)
            {
                pack.OnFile = (int sumCount, int curCount, string fileName) => ConsoleHelp.Log($"[{ curCount }/{sumCount} f]  " + fileName);
            }



            if (progress != null)
            {
                pack.progressStep = progress.Value;
                pack.OnProgress   = (float pro, int sumCount, int curCount) => { ConsoleHelp.Log($"[{curCount}/{sumCount}] 已完成 { pro * 100 } %"); };
            }

            pack.Pack();


            ConsoleHelp.Log("文件压缩成功!!!");

            #endregion
        }