Home
Manage Your Code
Snippet: Running a command line utility from C# (C#)
Title: Running a command line utility from C# Language: C#
Description: How to run a command line utility from C#. In this case, I needed to do a secure file copy to a remote server for an activiry report. I chose to use pscp from PuTTY. Views: 197
Author: digital Moto Date Added: 10/9/2008
Copy Code  
1string cmd = "pscp";
2string arguments = String.Format("-v -pw {0} \"{1}\" {2}@{3}:{4}",
3  _pwd,
4  activityReport.UploadFilename,
5  _uid,
6  _url,
7  _uploadDir
8);
9
10ProcessStartInfo psi = new ProcessStartInfo();
11psi.FileName = cmd;
12psi.Arguments = arguments;
13
14Logger.Debug(psi.FileName + " " + psi.Arguments);
15
16psi.RedirectStandardOutput = true;
17psi.RedirectStandardError = true;
18
19psi.WindowStyle = ProcessWindowStyle.Normal;
20psi.UseShellExecute = false;
21
22Process listFiles = Process.Start(psi);
23StreamReader myOutput = listFiles.StandardOutput;
24StreamReader myError = listFiles.StandardError;
25
26listFiles.WaitForExit(10 * 60 * 1000);  // timeout when?

27
28if (listFiles.HasExited)
29{
30  // did it exit gracefully?

31  Logger.Debug(myOutput.ToString() + myError.ToString());
32  listFiles.Close();
33} 
34else 
35{
36  // or did it timeout and need to kill it.

37  listFiles.Kill();
38  listFiles.Close();
39  throw new Exception("Upload timed out. " + myOutput.ToString() + myError.ToString());
40}
Usage
using System.IO;

// min to run.  
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = 
psi.Arguments = 
Process listFiles = Process.Start(psi);
Notes
If you want to run pscp, make sure you run this once from a regular dos prompt. If you don't you will not have to the certificate to upload the file. When debugging this kind of stuff, make sure you capture the output from S/Out and S/Err. I redirected them and sent the output back to a multiline textbox. If the called utiltiy hangs, you need to explicitly kill it. Otherwise it lingers and lingers and lingers...