Microsoft KB Archive/305994

= How To Write a Wrapper for a Command-Line Tool with Visual C# .NET =

Article ID: 305994

Article Last Modified on 7/15/2004

-

APPLIES TO


 * Microsoft Visual C# .NET 2002 Standard Edition

-



This article was previously published under Q305994



This article refers to the following Microsoft .NET Framework Class Library namespaces:
 * System.IO
 * System.Diagnostics

IN THIS TASK
 SUMMARY

Build the Code for the Wrapper Use the Wrapper in Your Application





SUMMARY
This step-by-step article describes how to write a wrapper for a command-line utility that you want to use as an Automation object in Visual C# .NET and the Microsoft .NET framework with Visual Studio.

To successfully build a wrapper for a command-line utility for use as an Automation object, you need to be able to start the process, and then you need to obtain the output from the execution of the process. This procedure is divided into the following sections:
 * Write the code for the wrapper:
 * Create a new class in which to house the wrapper code.
 * Add an internal method to this class that will house the actual functionality of the program.
 * Use the wrapper in your application:
 * Add your class file to a new application that will use this class.

back to the top

Build the Code for the Wrapper
To build the code for the wrapper, first create a new class in which to house the code. To do this, use Visual Studio or a text editor, such as Notepad, to create a new Visual C# .NET application.

Note: For the purposes of this article, the name of the sample Visual C# .NET application is LaunchEXE.

After you create the new class in which to house the code, add an internal method to this class that will house the actual functionality of the program. If you declare this method as internal, you can use it throughout your program; however, other applications outside of your program cannot access it.

To build the code:  Use the USING statement to declare to the compiler (refer to the first code fragment). The USING statement uses the resources of System.IO and System.Diagnostics in the following way:  System.IO: To read and write to a StreamWriter object. System.Diagnostics: To start an external process from the application.   Declare the LaunchEXE class, and declare the public member function, Run, of the LaunchEXE class. The Run method returns a string to the caller. This string holds the output from LaunchEXE after the string completes its work. The following list describes the three arguments for the Run function:  The first argument that is passed to the Run function is exeName; it is the name of the command-line tool application that you will start. This .exe file must reside in the same folder as the application that uses the class unless you specify a full path as another argument. In this article, assume that the .exe file is in the same folder as the application that you are building.</li> The second argument that is passed to the Run function is argsLine. This argument consists of a string that contains arguments that you will pass on to the command-line tool.</li> The third argument defines the time (in seconds) in which the .exe file must finish running, and return a result.</li></ul>

using System.Diagnostics; using System.IO; public class LaunchEXE { internal static string Run(string exeName, string argsLine, int timeoutSeconds) }                   </li> Prepare the StreamReader object to handle the output that is received from the executed command-line tool. The StreamReader object performs the following functions:  Reads the output that is created by the executable program.</li> Creates a string that contains the output from the executable program. This output will be sent back to the calling application.</li></ul> </li>  Set a Boolean value to FALSE, stating that this operation has not succeeded yet. You can set the Boolean value to TRUE after the operation completes successfully. StreamReader outputStream = StreamReader.Null; string output = &quot;&quot;; bool success = false; </li>  Create a new process object, and then pass the executable program (LauncheEXE), and the arguments (argsLine) to run the command-line utility. In this sample, the CreateNoWindow property is used so that the MS-DOS window is suppressed each time you invoke your class to start the executable program. try {   Process newProcess = new Process; newProcess.StartInfo.FileName = exeName; newProcess.StartInfo.Arguments = argsLine; newProcess.StartInfo.UseShellExecute = false; newProcess.StartInfo.CreateNoWindow = true; newProcess.StartInfo.RedirectStandardOutput = true; newProcess.Start; </li>  If the operation does not time out, obtain the output from the suppressed MS-DOS window of the command-line utility, and then destroy the objects: if (0 == timeoutSeconds) {       outputStream = newProcess.StandardOutput; output = outputStream.ReadToEnd; newProcess.WaitForExit; }   else {       success = newProcess.WaitForExit(timeoutSeconds * 1000); if (success) { outputStream = newProcess.StandardOutput; output = outputStream.ReadToEnd; } else {       output = &quot;Timed out at &quot; + timeoutSeconds + &quot; seconds waiting for &quot; + exeName + &quot; to exit.&quot;; } }

catch(Exception e) { throw (new Exception(&quot;An error occurred running &quot; + exeName + &quot;.&quot;,e)); } finally { outputStream.Close; }                   </li>  Return the output to the calling method: return &quot;\t&quot; + output; </li> Save the file as Start.cs.</li></ol>

This sample code provides an efficient way to wrap any command-line utility. In the application that you are writing, call the Run method of the LaunchEXE class and pass it any executable program with the appropriate arguments and Timeout value, and then parse the results in your own application.

back to the top

Use the Wrapper in Your Application
To use the wrapper, you have to add the class file to a new application that will use this class. You can also use this class in any other Visual C# .NET application. <ol> To integrate this class into your Visual Studio C# application: <ol style="list-style-type: lower-alpha;"> Start Visual Studio.</li> <li>Open the New Project dialog box. On the File menu, point to New, and then click Project.</li> <li>Select Visual C# Projects and for a template, select Windows Application.</li> <li>Type a name for your project in the Name text box, and then click OK. Visual Studio creates a new C# Windows application.</li> <li>In Solution Explorer, right-click your project name, point to Add, and then click Existing item. The Add Existing Item dialog box opens in Visual Studio. To add the C# class file to your application, browse to the folder in which you stored Start.cs, right-click Start.cs, and then click Open.</li></ol> </li> <li> To access the class in Start.cs from your application, make your class file a member of the namespace for your project: <ol style="list-style-type: lower-alpha;"> <li>In Solution Explorer, right-click the Form1.cs file that you created for your project, and then click View Code to open Form1.cs in the main window. At the top of the code file, you should see the word namespace, which is followed by your project name. Add this line in the same place in the Start.cs file.</li> <li>In Solution Explorer, right-click Start.cs, and then click View Code.</li> <li>Add the namespace line after the USING statements.

Your code should now resemble the following sample (in this sample, the project name is WindowsApplication1):</li></ol>

using System; using System.IO; using System.Diagnostics;

namespace WindowsApplication1 {   internal class LaunchEXE {       internal static string Run(string exeName, string argsLine, int timeoutSeconds) {       ...                    </li> <li>Make the class file a member of the namespace to create a reference to your class file, and then call the Run method: <ol style="list-style-type: lower-alpha;"> <li>Click the Form1.cs [Design] tab to view your form.</li> <li> Place a button on the form, and then call the Run method inside of the Click event for the button: <ol> <li>On the View menu, click Toolbox.</li> <li>Drag a button control onto the form. Double-click the button to start the code editor in which Visual Studio has created an event handler that you use to place your code for the Click event for the button. It should be placed within a code section that resembles the following sample:</li></ol>

private void button1_Click(object sender, System.EventArgs e) { }                       </li></ol> </li> <li> Add the following code to the event handler to call the Run function: private void button1_Click(object sender, System.EventArgs e) { string output; output = LaunchEXE.Run(&quot;CommandLineTool.exe&quot;, &quot;arg1 arg2&quot;, 10); System.Windows.Forms.MessageBox.Show(output); } In the first line of this code, you declare a new variable, which is named output, that you use to store the result of the command-line tool. In the second line, you state that the output variable is equal to that which the Run method returns. On this line you also specify that you want to start CommandLineTool.exe (which you can replace with the name of your own command-line tool). You pass the command-line tool two arguments, arg1 and arg2 (which you can replace with the name of the arguments that you want to pass to your .exe program). The third argument, which is a value of 10, indicates that the command-line tool must complete within 10 seconds. The last line in this code sample creates a pop-up message in which the output from the command-line tool is displayed. </li> <li>Press F5 to run the application.</li> <li>Click the button on the form. Within 10 seconds, a pop-up message box should open and display the output from the command-line tool.</li></ol>

In a real application, you can parse the output that is returned from your command-line tool, and display it in a more friendly form to your users through the graphical user interface (GUI).

Keywords: kbhowto kbio kbdiagnostics KB305994

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.