Read without ads and support Scribd by becoming a Scribd Premium Reader.
 
It is normal practice to open the command prompt and executecommands. The command when executed shows the result onto thescreen. There are many commands that we execute daily such as dir,find etc. C# programmers have to code in diverse satiations. Asituation may arise when you want to execute a (shell) command fromthe C# application. Don’t Worry!!! Here is the code to do so…In the code given below we create a process i.e. a command processand then invoke the command that we want to execute. The result of the command is stored in a string variable, which can then be used forfurther references. The command execution can happen in two ways,
synchronously
and
asynchronously
. In the asynchronous commandexecution we just invoke the command execution using a thread thatruns independently.
usingSystem;usingSystem.Threading; namespaceExecuteCommand{ public class Program { static voidMain(string[] args) { stringcommand =String.Empty;  // Write to the console. Console.Write("Enter the command you wish to execute: ");  // Get the command you wish to execute.command =Console.ReadLine().Trim(); 
 
 // Execute the command synchronously. ExecuteCmdexe =new ExecuteCmd(); exe.ExecuteCommandSync(command); // Execute the command asynchronously.exe.ExecuteCommandAsync(command); // Your' done !!! Console.WriteLine("\nDone !");  Console.ReadLine();}} public class ExecuteCmd {#regionExecuteCommand Sync and Async /// <summary>  ///Executes a shell command synchronously. /// </summary>  /// <param name="command">string command</param>  /// <returns>string, as output of the command.</returns>  public voidExecuteCommandSync(objectcommand) { try{ // create the ProcessStartInfo using "cmd" as theprogram to be run, and "/c " as the parameters. // Incidentally, /c tells cmd that we want it toexecute the command that follows, and then exit.
 
System.Diagnostics.ProcessStartInfoprocStartInfo =new System.Diagnostics.ProcessStartInfo("cmd","/c "+ command);  // The following commands are needed to redirect thestandard output.//This means that it will be redirected to theProcess.StandardOutput StreamReader.procStartInfo.RedirectStandardOutput =true;procStartInfo.UseShellExecute =false; // Do not create the black window.procStartInfo.CreateNoWindow =true; // Now we create a process, assign its ProcessStartInfoand start itSystem.Diagnostics.Processproc =new System.Diagnostics.Process();proc.StartInfo = procStartInfo;proc.Start(); // Get the output into a string stringresult = proc.StandardOutput.ReadToEnd(); // Display the command output. Console.WriteLine(result);} catch(ExceptionobjException) { // Log the exception}} /// <summary> ///Execute the command Asynchronously.
Search History:
Searching...
Result 00 of 00
00 results for result for
  • p.
  • Notes
    Load more