{"id":169,"date":"2012-03-05T20:07:14","date_gmt":"2012-03-05T12:07:14","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=169"},"modified":"2018-09-03T21:34:11","modified_gmt":"2018-09-03T13:34:11","slug":"how-to-interact-with-applications-via-command-line-in-c","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-interact-with-applications-via-command-line-in-c\/","title":{"rendered":"How to interact with applications via command line in C#"},"content":{"rendered":"<p>As with most programming languages, C# has the facilities to start other applications via command line. Such facilities may not be of much interest to the ardent C# programmer, who will want to fulfill every business logic with purely C# codes in his\/her program. However, there are times when it is necessary to interface with applications that other people had already built for us.<\/p>\n<h3>Why do we have to leverage on applications via command line in C#?<\/h3>\n<p>We may have to do so because of the following reasons:<\/p>\n<ul>\n<li>An application had cost too much in the past and business wants to avoid spending additional time and resources to replicate its functionality in C#.<\/li>\n<li>The third party vendor gave an C# api which had broken functionailities and the command line tool that they provide is the only option that can be leveraged on.<\/li>\n<li>There are certain functionalities that is not available (or easily available) in C# but is a given in windows through its huge application repository.<\/li>\n<\/ul>\n<p>In this post, I document three examples on how we can interface with other applications via command line in C#.<\/p>\n<h3>Start a web browser to display a webpage from C#<\/h3>\n<p>Let's start off with a minimal example. Let's assume that I wish to show my website from my C# program.<\/p>\n<p>That would be a similar to typing <code>iexplore http:\/\/www.techcoil.com<\/code> in the command prompt to start internet explorer to show the home page of my website.<\/p>\n<h4>What happens when we do that?<\/h4>\n<p>That is actually an example of command line execution. We are actually requesting the operating system to start a <strong>process<\/strong> to run <code>iexplore<\/code> (the executable for Internet Explorer), giving it <code>http:\/\/www.techcoil.com<\/code> as a <strong>command line argument<\/strong>.<\/p>\n<p>The following code segment is how we could do that in C#:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nusing System;\r\nusing System.Diagnostics;\r\nusing System.Text;\r\npublic class LaunchInternetExplorer\r\n{\r\n    public static void Main(string&#x5B;] args)\r\n    {\r\n        Process ieProcess = new Process();\r\n        \/\/ Set the application that our Process is\r\n        \/\/ going to start.\r\n        ieProcess.StartInfo.FileName = &quot;iexplore&quot;;\r\n        \/\/ Pass in the url that iexplore will visit upon\r\n        \/\/ starting as a command line argument.\r\n        ieProcess.StartInfo.Arguments = &quot;http:\/\/www.techcoil.com&quot;;\r\n        \/\/ Start the command line execution\r\n        ieProcess.Start();\r\n    } \/\/ public static void Main(string&#x5B;] args)\r\n} \/\/ end public class LaunchInternetExplorer\r\n<\/pre>\n<p>This code segment began with creating an instance of the <a title=\"MSDN reference for System.Diagnostic.Process\" href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.diagnostics.process.aspx\" target=\"_blank\"><code>System.Diagnostic.Process<\/code><\/a> class.<\/p>\n<p>The name of the application (iexplore) to start on command line is then set via the <code>ieProcess.StartInfo.FileName<\/code> property. After that, the url to techcoil is provided as a command line argument via the <code>ieProcess.StartInfo.Arguments<\/code> property.<\/p>\n<p>When the relevant <strong>start up information<\/strong> is provided via the <code>ieProcess.StartInfo<\/code> property, we start the process to launch internet explorer by calling <code>ieProcess.Start()<\/code>.<\/p>\n<h4>So what is <code>ieProcess.StartInfo<\/code>?<\/h4>\n<p>When we get our <code>Process<\/code> instance, we also get an instance of the <a title=\"MSDN reference for System.Diagnostic.ProcessStartInfo\" href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.diagnostics.processstartinfo.aspx\" target=\"_blank\"><code>System.Diagnostics.ProcessStartInfo<\/code><\/a>, which contains startup information for the process when it starts running. This <code>ProcessStartInfo<\/code> instance is accessible via the <a title=\"MSDN reference for Process.StartInfo property\" href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.diagnostics.process.startinfo.aspx\" target=\"_blank\"><code>StartInfo<\/code><\/a> property of our Process instance.<\/p>\n<h3>Reading from standard output of command line application in C#<\/h3>\n<p>Unless our C# program is able to <a title=\"A mechanism for serving HTTP requests in C#\" href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/a-mechanism-for-serving-http-requests-in-c\/\" target=\"_blank\">serve HTTP requests<\/a> and we point internet explorer to its url, we are not interacting with the internet explorer process anymore in our previous code example.<\/p>\n<p>However, there are times when we want to read the standard output of an application that we started from command line. <\/p>\n<p>The following code segment demonstrates how we can read from the standard output of the <a title=\"Microsoft Windows XP Professional documentation for ipconfig\" href=\"http:\/\/www.microsoft.com\/resources\/documentation\/windows\/xp\/all\/proddocs\/en-us\/ipconfig.mspx?mfr=true\" target=\"_blank\">ipconfig<\/a> command:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nusing System;\r\nusing System.Diagnostics;\r\nusing System.IO;\r\nusing System.Text;\r\npublic class ReadFromStandardOutput\r\n{\r\n    public static void Main(string&#x5B;] args)\r\n    {\r\n        Process ipconfigProcess = new Process();\r\n        \/\/ Indicate that we want to execute ipconfig\r\n        ipconfigProcess.StartInfo.FileName = &quot;ipconfig&quot;;\r\n        ipconfigProcess.StartInfo.Arguments = &quot;\/all&quot;;\r\n        \/\/ Indicate that we want to read the command line output\r\n        ipconfigProcess.StartInfo.RedirectStandardOutput = true;\r\n        ipconfigProcess.StartInfo.UseShellExecute = false;\r\n        \/\/ Start the process to execute ipconfig\r\n        ipconfigProcess.Start();\r\n        \/\/ Get a StreamReader to read from the standard output of\r\n        \/\/ the ipconfig process\r\n        StreamReader reader = ipconfigProcess.StandardOutput;\r\n        \/\/ Perform reading and writing of standard output to Console\r\n        String line;\r\n        while((line = reader.ReadLine()) != null) {\r\n            Console.WriteLine(line);\r\n        } \/\/ end while\r\n    } \/\/ end public static void Main(string&#x5B;] args)\r\n} \/\/ end public class ReadFromStandardOutput\r\n<\/pre>\n<p>In this case, we are getting our C# program to execute <code>ipconfig \/all<\/code>, which will display current TCP\/IP network configurations for all adapters in our windows machine.<\/p>\n<p>As with the internet explorer example, the above program first creates an instance of <code>Process<\/code> and then supplies it with the application name to run and a command line argument string.<\/p>\n<p>In addition to that, two other properties are being set - <a title=\"MSDN reference for System.Diagnostics.ProcessStartInfo.RedirectStandardOutput property\" href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.diagnostics.processstartinfo.redirectstandardoutput.aspx\" target=\"_blank\"><code>StartInfo.RedirectStandardOutput<\/code><\/a> and <a title=\"MSDN reference for System.Diagnostics.ProcessStartInfo.UseShellExecute Property\" href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.diagnostics.processstartinfo.useshellexecute.aspx\" target=\"_blank\"><code>StartInfo.UseShellExecute<\/code><\/a>.<\/p>\n<p>We set <code>RedirectStandardOutput<\/code> to true because we want to be able to read from standard output; set <code>UseShellExecute<\/code> to false because we <strong>cannot use<\/strong> the operating system shell to execute the command line application if we want to get its standard output.<\/p>\n<p>When start information about the process had been provided to the <code>Process<\/code> instance, we start the process to execute <code>ipconfig \/all<\/code> via command line.<\/p>\n<p>Finally, we get a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.streamreader.aspx\" title=\"MSDN reference for System.IO.StreamReader\" target=\"_blank\"><code>System.IO.StreamReader<\/code><\/a> instance from the StandardOutput property and use it to read the standard output, just like how we would <a title=\"How to read from file in C#\" href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-read-from-file-in-c\/\" target=\"_blank\">read text from file<\/a>.<\/p>\n<h3>Writing to standard input of command line application in C#<\/h3>\n<p>Sometimes, our C# program will need to interact with command line applications that collect input from the user through a command line interface. To interact with such application, we need to write to the standard input of the command line application.<\/p>\n<p>Let's assume we have the following command line application, <code>Greeter.exe<\/code>, that greets the user after asking for his\/her name:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic class Greeter\r\n{\r\n    public static void Main(string&#x5B;] args)\r\n    {\r\n        Console.WriteLine(&quot;What's your name? &quot;);\r\n        String name = Console.ReadLine();\r\n        Console.WriteLine(&quot;Hello &quot; + name + &quot;. Nice to meet you!&quot;);\r\n    } \/\/ end public static void Main(string&#x5B;] args)\r\n} \/\/ end public class Greeter\r\n<\/pre>\n<p>And right now, we want to interface with it from another C# program. The following code demonstrates how we can do so by writing to the standard input and reading from the standard output of <code>Greeter.exe<\/code>.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic class WriteToStandardInputOfGreeter\r\n{\r\n    public static void Main(string&#x5B;] args)\r\n    {\r\n        Process greeterProcess = new Process();\r\n        greeterProcess.StartInfo.FileName = &quot;Greeter.exe&quot;;\r\n        \/\/ Indicate that we want to read from standard output\r\n        \/\/ of process\r\n        greeterProcess.StartInfo.RedirectStandardInput = true;\r\n        \/\/ Indicate that we want to write to standard input of\r\n        \/\/ process\r\n        greeterProcess.StartInfo.RedirectStandardOutput = true;\r\n        greeterProcess.StartInfo.UseShellExecute = false;\r\n        greeterProcess.Start();\r\n        \/\/ Get a StreamWriter to write to the standard input of\r\n        \/\/ Greeter.exe\r\n        StreamWriter writer = greeterProcess.StandardInput;\r\n        \/\/ Get a StreamReader to read from standard output of\r\n        \/\/ Greeter.exe\r\n        StreamReader reader = greeterProcess.StandardOutput;\r\n        \/\/ Get the question from greeter\r\n        Console.WriteLine(&quot;Question from greeter: &quot;);\r\n        Console.WriteLine(reader.ReadLine());\r\n        \/\/ Answer Greeter with Robot\r\n        writer.WriteLine(&quot;Robot&quot;);\r\n        Console.WriteLine(&quot;Response from greeter: &quot;);\r\n        Console.WriteLine(reader.ReadLine());\r\n    } \/\/ end public static void Main(string&#x5B;] args)\r\n} \/\/ end public class WriteToStandardInputOfGreeter\r\n<\/pre>\n<p>Similar to the first two examples, the program begins with creating an instance of the <code>Process<\/code> class.<\/p>\n<p>Four pieces of start information are then supplied to the <code>Process<\/code> instance:<\/p>\n<ol>\n<li>Name of the command line application to run, Greeter.exe, via the <code>StartInfo.FileName<\/code> property.<\/li>\n<li>Indication for <strong>standard input redirection<\/strong>, via the <code>StartInfo.RedirectInputOutput<\/code> property.<\/li>\n<li>Indication for <strong>standard output redirection<\/strong>, via the <code>StartInfo.RedirectStandardOutput<\/code> property.<\/li>\n<li>Indication for <strong>not using<\/strong> the operating system shell, via the <code>StartInfo.UseShellExecute<\/code> property, so that our C# program can read from the standard output and write to the standard input of <code>Greeter.exe<\/code>.<\/li>\n<\/ol>\n<p>The process is then started with a call to the <code>greeterProcess.Start<\/code>.<\/p>\n<p>After the process had started, we first get an instance of <code>StreamReader<\/code> via the <code>greeterProcess.StandardOutput<\/code> property and an instance of <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.streamwriter.aspx\" title=\"MSDN reference for System.IO.StreamWriter\" target=\"_blank\"><code>System.IO.StreamWriter<\/code><\/a> via the <code>greeterProcess.StandardInput<\/code> property.<\/p>\n<p>We then use the StreamReader instance to read the prompt for name input from Greeter.exe, write Robot to its Standard Input and read its response, which is the string \"Hello Robot. Nice to meet you!\". <\/p>\n<h3>Posts that may interest you<\/h3>\n<ul>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-execute-codes-periodically-in-c\/\" title=\"How to execute codes periodically in C#\" target=\"_blank\">How to execute codes periodically in C#<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-save-and-load-objects-to-and-from-file-in-c\/\" title=\"How to save and load objects to and from file in C#\" target=\"_blank\">How to save and load objects to and from file in C#<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/designing-command-line-applications-for-scheduled-execution\/\" title=\"Designing command-line applications for scheduled execution\" target=\"_blank\">Designing command-line applications for scheduled execution<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/a-mechanism-for-serving-http-requests-in-c\/\" title=\"A mechanism for serving HTTP requests in C#\" target=\"_blank\">A mechanism for serving HTTP requests in C#<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/implementing-client-server-communication-using-serialization-and-tcpip-in-c\/\" title=\"Implementing client-server communication using serialization and TCP\/IP in C#\" target=\"_blank\">Implementing client-server communication using serialization and TCP\/IP in C#<\/a><\/li>\n<\/ul>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-2J\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-2J&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-2J&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F169&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>As with most programming languages, C# has the facilities to start other applications via command line. Such facilities may not be of much interest to the ardent C# programmer, who will want to fulfill every business logic with purely C# codes in his\/her program. However, there are times when it is necessary to interface with applications that other people had already built for us.<\/p>\n","protected":false},"author":1,"featured_media":1189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[20,99,84,97],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/C-Sharp-Logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-2J","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/169"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=169"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/169\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1189"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=169"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=169"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=169"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}