Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# executing cmd command not working

Tags:

c#

.net

wpf

Can anybody suggest why the following code not returning system date?

 ProcessStartInfo cmdInfo = new ProcessStartInfo("cmd.exe", "net time \\192.168.221.1");
            cmdInfo.CreateNoWindow = true;
            cmdInfo.RedirectStandardOutput = true;
            cmdInfo.RedirectStandardError = true;
            cmdInfo.UseShellExecute = false;

            Process cmd = new Process();
            cmd.StartInfo = cmdInfo;
            var output = new StringBuilder();
            var error = new StringBuilder();

            cmd.OutputDataReceived += (o, e) => output.Append(e.Data);
            cmd.ErrorDataReceived += (o, e) => error.Append(e.Data);

            cmd.Start();
            cmd.BeginOutputReadLine();
            cmd.BeginErrorReadLine();
            cmd.WaitForExit();
            cmd.Close();
            var s = output;
            var d = error;

Output is

{Microsoft Windows [Version 6.1.7601]Copyright (c) 2009 Microsoft Corporation.  All rights reserved.D:\TEST\TEST\bin\Debug>}
like image 835
Matt Avatar asked Jul 08 '26 17:07

Matt


1 Answers

Try with this

ProcessStartInfo cmdInfo = new ProcessStartInfo("cmd.exe", "/C net time \\\\192.168.221.1");

You need to add the /C switch to catch the output of running command inside the CMD shell.
Also the backslash should be doubled or use the string Verbatim prefix @

like image 131
Steve Avatar answered Jul 11 '26 17:07

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!