I am making an application which allows a client to list all their running processes in a dialog box. I currently have the below code, and I can't work out why it isn't working.
I am not seeing any output whatsoever, be it sderr or stdout. Can someone please point me in the right direction?
private void button1_Click(object sender, EventArgs e)
{
string test = " ";
var ss = new SecureString();
ss.AppendChar('T');
ss.AppendChar('a');
ss.AppendChar('k');
ss.AppendChar('e');
ss.AppendChar('c');
ss.AppendChar('a');
ss.AppendChar('r');
ss.AppendChar('e');
ss.AppendChar('9');
ss.AppendChar('9');
ss.MakeReadOnly();
var serverName = "SERVER-NAME";
var sessionID = "2";
var PID = "6816";
var startInfo = new ProcessStartInfo("cmd", "/C tasklist /S " + serverName + " /FI \"SESSION eq " + sessionID + "\" >C:\\users\\test.account\\desktop\\NEWEWE.txt")
{
WorkingDirectory = @"C:\windows\system32",
Verb = "runas",
Domain = "BARDOM1",
UserName = "XATest",
Password = ss,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
var proc = Process.Start(startInfo);
proc.OutputDataReceived += (x, y) => test += (y.Data);
proc.BeginOutputReadLine();
proc.WaitForExit();
MessageBox.Show(test);
MessageBox.Show("done");
}
I have tried redirect output set to true
and false
, and I have tried setting the >c:\...
in the CMD command with various properties, but can't see any output at all.
The problem is that the command line specifies that the output should go to a file. I'd also recommend the use of a StringBuilder
for collecting the output. It's a lot more efficient than concatenating strings with +=
.
Here's an example that shows the working version, followed by a version that exhibits the behavior you were seeing.
StringBuilder test = new StringBuilder();
// Not redirected
ProcessStartInfo psi = new ProcessStartInfo("cmd", "/c echo yes")
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
Process proc = Process.Start(psi);
proc.OutputDataReceived += (x, y) => test.Append(y.Data);
proc.BeginOutputReadLine();
proc.WaitForExit();
Console.WriteLine(test.ToString()); // Output: yes
test.Clear();
// Redirected
psi = new ProcessStartInfo("cmd", "/c echo yes > NUL")
{
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
proc = Process.Start(psi);
proc.OutputDataReceived += (x, y) => test.Append(y.Data);
proc.BeginOutputReadLine();
proc.WaitForExit();
Console.WriteLine(test.ToString()); // Blank line