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>}
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 #
Related
I have following C# lines of code where open process and run dotnet command to open my console application (created with .net standard/core)
var args = new Dictionary<string, string> {
{ "-p", "title"},
{ "-l", "games"},
...
};
var arguments = string.Join(" ", args.Select((k) => string.Format("{0} {1}", k.Key, "\"" + k.Value + "\"")));
var dllPath = #"C:\Users\xyz\Documents\Visual Studio 2017\myConsole\bin\Debug\netcoreapp2.1\myConsole.dll";
ProcessStartInfo procStartInfo = new ProcessStartInfo();
procStartInfo.FileName = "C:\....\cmd.exe";
procStartInfo.Arguments = $"dotnet \"{dllPath}\" {arguments}";
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
StringBuilder sb = new StringBuilder();
Process pr = new Process();
pr.StartInfo = procStartInfo;
pr.OutputDataReceived += (s, ev) =>
{
if (string.IsNullOrWhiteSpace(ev.Data))
{
return;
}
string[] split = ev.Data.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
int.TryParse(split[split.Length - 1], out output);
};
pr.ErrorDataReceived += (s, err) =>
{
// do stuff here
};
pr.EnableRaisingEvents = true;
pr.Start();
pr.BeginOutputReadLine();
pr.BeginErrorReadLine();
pr.WaitForExit();
The command Arguments result is:
dotnet "C:\Users\xyz\Documents\Visual Studio 2017\myConsole\bin\Debug\netcoreapp2.1\myConsole.dll" -p "title" -l "games" -s "" -r "none" -k "0" -d "/path/" -f ""
But for ev.Data from OutputDataReceived event looks like:
Microsoft Windows [Version 10.0.16299.665]
(c) 2017 Microsoft Corporation. All rights reserved.
and that's all...
I expected to run dotnet command to dll.
If I run manually the result command dotnet .... above, works fine. But not from my C# code. Why ?
Because cmd returns:
Microsoft Windows [Version 10.0.16299.665]
(c) 2017 Microsoft Corporation. All rights reserved.
You need to call
procStartInfo.FileName = "dotnet"
I have function that get me a whole cmd
public void GetMovieData(string FileName)
{
string command = "mediainfo --Inform=file://custom.txt " + FileName;
ProcessStartInfo psi = new ProcessStartInfo();
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.FileName = "cmd.exe";
psi.UseShellExecute = false;
using (Process p = Process.Start(psi))
{
p.StandardInput.Flush();
p.StandardInput.WriteLine(command);
p.StandardInput.Flush();
p.StandardInput.Close();
t_Dane_tech.Text = p.StandardOutput.ReadToEnd();
}
}
now i want only get these lines that are below command. Now when i hit the button i get info: Microsoft Windows [Version 10.0.16299.309]
(c) 2017 Microsoft Corporation bla bla bla and result of my command. I just want that command result... It can be done?
string command = "mediainfo --Inform=file://custom.txt " + FileName + " > "plik.txt";
And now streamreader and at the end of the function delete file. I think i overthink it but it is just fine :D
In C# WPF: I want to execute a CMD command, how exactly can I execute a cmd command programmatically?
Here's a simple example :
Process.Start("cmd","/C copy c:\\file.txt lpt1");
As mentioned by the other answers you can use:
Process.Start("notepad somefile.txt");
However, there is another way.
You can instance a Process object and call the Start instance method:
Process process = new Process();
process.StartInfo.FileName = "notepad.exe";
process.StartInfo.WorkingDirectory = "c:\temp";
process.StartInfo.Arguments = "somefile.txt";
process.Start();
Doing it this way allows you to configure more options before starting the process. The Process object also allows you to retrieve information about the process whilst it is executing and it will give you a notification (via the Exited event) when the process has finished.
Addition: Don't forget to set 'process.EnableRaisingEvents' to 'true' if you want to hook the 'Exited' event.
if you want to start application with cmd use this code:
string YourApplicationPath = "C:\\Program Files\\App\\MyApp.exe"
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.FileName = "cmd.exe";
processInfo.WorkingDirectory = Path.GetDirectoryName(YourApplicationPath);
processInfo.Arguments = "/c START " + Path.GetFileName(YourApplicationPath);
Process.Start(processInfo);
Using Process.Start:
using System.Diagnostics;
class Program
{
static void Main()
{
Process.Start("example.txt");
}
}
How about you creat a batch file with the command you want, and call it with Process.Start
dir.bat content:
dir
then call:
Process.Start("dir.bat");
Will call the bat file and execute the dir
You can use this to work cmd in C#:
ProcessStartInfo proStart = new ProcessStartInfo();
Process pro = new Process();
proStart.FileName = "cmd.exe";
proStart.WorkingDirectory = #"D:\...";
string arg = "/c your_argument";
proStart.Arguments = arg;
proStart.WindowStyle = ProcessWindowStyle.Hidden;
pro.StartInfo = pro;
pro.Start();
Don't forget to write /c before your argument !!
Argh :D not the fastest
Process.Start("notepad C:\test.txt");
Are you asking how to bring up a command windows? If so, you can use the Process object ...
Process.Start("cmd");
You can do like below:
var command = "Put your command here";
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.WorkingDirectory = #"C:\Program Files\IIS\Microsoft Web Deploy V3";
procStartInfo.CreateNoWindow = true; //whether you want to display the command window
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
label1.Text = result.ToString();
In addition to the answers above, you could use a small extension method:
public static class Extensions
{
public static void Run(this string fileName,
string workingDir=null, params string[] arguments)
{
using (var p = new Process())
{
var args = p.StartInfo;
args.FileName = fileName;
if (workingDir!=null) args.WorkingDirectory = workingDir;
if (arguments != null && arguments.Any())
args.Arguments = string.Join(" ", arguments).Trim();
else if (fileName.ToLowerInvariant() == "explorer")
args.Arguments = args.WorkingDirectory;
p.Start();
}
}
}
and use it like so:
// open explorer window with given path
"Explorer".Run(path);
// open a shell (remanins open)
"cmd".Run(path, "/K");
I have a console application that executes some commands and outputs some logs.
I need the output that display the command and its result, like this one:
>Loading the database...
>mysql -uUser -pPassword myDbName < mydumpFile
ERROR 1045 (28000): Access denied for user 'User'#'localhost' (using password: Y
ES)
>End loading the databse...
I did the folowing:
void ImportData()
{
Program.Log("INFO", "Start importing data... <<<");
Process myProcess = new Process();
string mySqlArgs = string.Format(" -u{0} -p{1} {2} < \"{3}\"",
bddUser, bddPassword, databaseName, dumpPath);
ProcessStartInfo myProcessStartInfo =
new ProcessStartInfo("mysql", mySqlArgs);
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();
StreamReader reader = myProcess.StandardOutput;
string theOutput = reader.ReadToEnd();
if (theOutput.Length > 0)
Program.Log("SQL", theOutput);
Program.Log("INFO", "END importing data >>>");
}
but this code
1) does not display the command itself (just the result)
2) the request perhaps should be bad formatted, because the result is like a format error in the mysql command
UPDATE: the new code is a litte bit better
Program.Log("INFO", "Start importing Materials... <<<".Fill(code));
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
/* execute "mysql -uUser -pPassword base < dump" */
string mySqlCommand = "mysql -u{0} -p{1} {2} < \"{3}\"";
cmd.StandardInput.WriteLine(mySqlCommand, bddUser, bddPassword, databaseName, dumpPath);
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
StreamReader reader = cmd.StandardOutput;
string theOutput = reader.ReadToEnd();
if (theOutput.Length > 0)
Program.Log("SQL", Environment.NewLine + theOutput);
Program.Log("INFO", "END importing Materials >>>".Fill(code));
, but anyway, it displays additional information from the cmd.exe first execution (before mysql command) and also the command line after the mysql command result...
Execute the script as
mysql -vvv -uUser ...
this Option will Display the queries during execution of the script.
As for your other Problem: Why do you call a cmd.exe? Just call mysql.exe directly from your program and skip the shell...
I have a scenario where I am reading a file on an android phone from a C# application by using adb.exe to get in to the phone's shell and reading the file by using a Process in the C# app. However, I need to use Thread.Sleep right before Process.Start here if I want it to actually work. Any ideas why?
Here is the code:
ProcessStartInfo cmdInfo;
string resulterr = "";
string result = "";
cmdInfo = new ProcessStartInfo(" adb.exe ", "shell cat /etc/bluetooth/bt_stack.conf");
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, ef) => output.Append(ef.Data);
cmd.ErrorDataReceived += (o, ef) => error.Append(ef.Data);
//if I don`t have this Thread.Sleep, the error string is "device not found"!!
Thread.Sleep(5000);
cmd.Start();
cmd.BeginOutputReadLine();
cmd.BeginErrorReadLine();
cmd.WaitForExit();
cmd.Close();
resulterr = error.ToString();
result = output.ToString();
cmd.Dispose();
Any ideas why this works with the thread sleeping but doesn`t work without it?? I can run
shell cat /etc/bluetooth/bt_stack.conf
from the command line ad naseaum with no delays and no issues -- why do I need them here??
Ok, in my case the device was actually not ready to receive the commands. I waited for a good device status like this.
ProcessStartInfo lcmdInfo1;
lcmdInfo1 = new ProcessStartInfo(" adb.exe ", "get-state");
lcmdInfo1.CreateNoWindow = true;
lcmdInfo1.RedirectStandardOutput = true;
lcmdInfo1.RedirectStandardError = true;
lcmdInfo1.UseShellExecute = false;
Process cmd2 = new Process();
cmd2.StartInfo = lcmdInfo1;
var output = new StringBuilder();
var error = new StringBuilder();
cmd2.OutputDataReceived += (o, ef) => output.Append(ef.Data);
cmd2.ErrorDataReceived += (o, ef) => error.Append(ef.Data);
cmd2.Start();
cmd2.BeginOutputReadLine();
cmd2.BeginErrorReadLine();
cmd2.WaitForExit();
cmd2.Close();
lresulterr1 = error.ToString();
lresult1 = output.ToString();
cmd2.Dispose();
//sometimes there is an issue with a previously issued command that causes the device status to be 'Unknown'. Wait until the device status is 'device'
while (!lresult1.Contains("device"))
{
lcmdInfo1 = new ProcessStartInfo(" adb.exe ", "get-state");
lcmdInfo1.CreateNoWindow = true;
lcmdInfo1.RedirectStandardOutput = true;
lcmdInfo1.RedirectStandardError = true;
lcmdInfo1.UseShellExecute = false;
cmd2 = new Process();
cmd2.StartInfo = lcmdInfo1;
output = new StringBuilder();
error = new StringBuilder();
cmd2.OutputDataReceived += (o, ef) => output.Append(ef.Data);
cmd2.ErrorDataReceived += (o, ef) => error.Append(ef.Data);
cmd2.Start();
cmd2.BeginOutputReadLine();
cmd2.BeginErrorReadLine();
cmd2.WaitForExit();
cmd2.Close();
lresulterr1 = error.ToString();
lresult1 = output.ToString();
cmd2.Dispose();
}
//now your device is ready. Go ahead and fire off the shell commands