Passing arguments to ProcessStartInfo class
-
14-06-2021 - |
Frage
i want to call the command prompt command using Process.Start and then using StandardOutput i want to read using StreamReader in my application but when i run the below program, in the MessageBox i just find the path till Debug, my command which i have stated in arguments does not exexutes.
ProcessStartInfo info = new ProcessStartInfo("cmd.exe", "net view");
info.UseShellExecute = false;
info.CreateNoWindow = true;
info.RedirectStandardOutput = true;
Process proc = new Process();
proc.StartInfo = info;
proc.Start();
using(StreamReader reader = proc.StandardOutput)
{
MessageBox.Show(reader.ReadToEnd());
}
here my net view command never executes.
Lösung
If you want to run a command with cmd
you have to specify the /c
argument too:
new ProcessStartInfo("cmd.exe", "/c net view");
In this case, however, you don't need cmd
at all. net
is a native program and can be executed as is, without a shell:
new ProcessStartInfo("net", "view");
Andere Tipps
Remember also to intercept the StandardErrorOutput or will see nothing:
var startInfo = new ProcessStartInfo("net", "view");
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
using (var process = Process.Start(startInfo))
{
string message;
using (var reader = process.StandardOutput)
{
message = reader.ReadToEnd();
}
if (!string.IsNullOrEmpty(message))
{
MessageBox.Show(message);
}
else
{
using (var reader = process.StandardError)
{
MessageBox.Show(reader.ReadToEnd());
}
}
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow