📜 ⬆️ ⬇️

Meaningful use of console applications in C #

When something is already written, tested and adequately copes with its work, it is better to use this tool rather than reinvent the wheel. For example, there is a console utility cpctest.exe , which allows you to perform all the same actions as the graphical shell, and many other utilities from the standard set of Windows. It will take valuable time to develop, debug, and cover tests of similar functionality. So why burn it? Let's get started

First we need to climb on MSDN and see the syntax of standard commands. As a result, we will see that the launch of any console application consists of the application name and its parameters. The application is instantiated by the system class Process . The prototype of our function for launching a console application will be as follows:

bool Execute(string commandName, IEnumerable<string> paramsList) 

If we want to get the result of executing a running application and process it, we will need an appropriate method:

 string GetResult (string commandName, IEnumerable<string> paramsList) 

Next, go back to MSDN and look at ProcessStartInfo Arguments , UseShellExecute , RedirectStandardOutput, and RedirectStandardError , if you strictly handle exceptions like in Java. As a result, to initialize the process, we need a property that will determine the launch mode of the console application and a method to initiate the process. For my class, I used the Facade pattern.
')
 public class CommandHelpers { public CommandHelpers() { Invisible = true; } public bool Invisible { get; set; } private Process CreateProcess(string commandName, IEnumerable<string> paramsList, bool output = false) { string paramString = paramsList.Aggregate<string, string>(null, (current, param) => current + " " + param); return new Process { StartInfo = { FileName = commandName, Arguments = paramString, UseShellExecute = output ? !output : !Invisible, RedirectStandardOutput = output } }; } 

It should be noted that the application being launched may run indefinitely, for example, ping –t youwebsite.org. To start it, we need the appropriate method:

 public Task<bool> ExecuteAsync(string commandName, IEnumerable<string> paramsList) 

Source:

Usage example:
 public class CspHelpers { private readonly CommandHelpers _cryptoconsole; private readonly string _command = @"c:\Program Files\Crypto Pro\CSP\csptest"; public CspHelpers() { _cryptoconsole = new CommandHelpers(); } /// <summary> ///     /// </summary> /// <param name="driveName">  </param> /// <param name="containerName"> </param> /// <param name="type">   exchange  signature</param> /// <param name="certPath">   </param> /// <param name="password">  </param> /// <returns>  </returns> public string ImportToContainer(string driveName, int containerName, KeyType type, string certPath, string password) { var Params = new List<string>(); Params.Add("-keyset"); Params.Add("-container"); Params.Add(string.Format(@"\\.\FAT12_{0}\{1}", driveName[0], containerName)); Params.Add("-password"); Params.Add(password); Params.Add("-keytype"); Params.Add(type.ToString()); Params.Add("-impcert"); Params.Add(certPath); return _cryptoconsole.GetResult(_command, Params); } } 


CommandHelpers.cs
 using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Common.Security { /// <summary> /// See for correct use https://technet.microsoft.com/en-us/library/bb491070.aspx /// </summary> public class CommandHelpers { public CommandHelpers() { Invisible = true; } /// <summary> /// Not show CMD window /// </summary> public bool Invisible { get; set; } /// <summary> /// Execete CMD command /// </summary> /// <param name="commandName">Command name only</param> /// <param name="paramsList">Params and keys for command</param> public bool Execute(string commandName, IEnumerable<string> paramsList) { return CreateProcess(commandName, paramsList).Start(); } /// <summary> /// Async execete CMD command /// </summary> /// <param name="commandName">Command name only</param> /// <param name="paramsList">Params and keys for command</param> public Task<bool> ExecuteAsync(string commandName, IEnumerable<string> paramsList) { return Task<bool>.Factory.StartNew(() => CreateProcess(commandName, paramsList).Start()); } /// <summary> /// Returns result of command execution /// </summary> /// <param name="commandName">Command name only</param> /// <param name="paramsList">Params and keys for command</param> /// <returns></returns> public string GetResult(string commandName, IEnumerable<string> paramsList) { var bufer = new StringBuilder(); using (var proc = CreateProcess(commandName, paramsList, true)) { proc.Start(); while (!proc.StandardOutput.EndOfStream) { bufer.AppendLine(proc.StandardOutput.ReadLine()); } } return bufer.ToString(); } /// <summary> /// Returns result of command execution /// Experemental. Not Tested. /// </summary> /// <param name="commandName">Command name only</param> /// <param name="paramsList">Params and keys for command</param> /// <returns></returns> public string GetResultAsync(string commandName, IEnumerable<string> paramsList) { var bufer = new StringBuilder(); using (var proc = CreateProcess(commandName, paramsList, true)) { proc.OutputDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { bufer.AppendLine(e.Data); } }; proc.BeginOutputReadLine(); proc.EnableRaisingEvents = true; proc.WaitForExit(); } return bufer.ToString(); } private Process CreateProcess(string commandName, IEnumerable<string> paramsList, bool output = false) { var paramString = paramsList.Aggregate<string, string>(null, (current, param) => current + " " + param); return new Process { StartInfo = { FileName = commandName, Arguments = paramString, UseShellExecute = output ? !output : !Invisible, RedirectStandardOutput = output } }; } } } 


UPD:

Additional materials:

Source of inspiration for the article:
From vedmaka : toster.ru/q/7644

GUI wrapper for console application: en.jakeroid.com/gui-obertka-dlya-konsolnogo-prilozheniya-na-csharp.html

From evgenyl : habrahabr.ru/post/136766

Source: https://habr.com/ru/post/276443/


All Articles