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...
Related
I tried to get the output of passed argument in the cmd.exe via c# code. But when the code string outw = cmd.StandardOutput.ReadToEnd().ToString(); executing takes more and more time. Here my command prompt arguments work perfectly.
Here is my 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();
cmd.StandardInput.WriteLine("git init && git remote add gitlab https://gitlab.company.com/test2.git && git push gitlab --delete branchname");
cmd.StandardInput.WriteLine("git remote remove gitlab");
string outw = cmd.StandardOutput.ReadToEnd().ToString();//Here my code strucks
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
Where I made the mistake? I waited for more than 30 min but I did not get the output in the string outw. How could I get the output test as a string in string outw?
I'm trying to run a batch file with arguments and also redirect the output.
When I don't redirect the output and use UseShellExecute = true, the batch file runs with the arguments as expected.
When I use UseShellExecute = false (to do the redirect), then I see that the command-line opens for a split a second and then closes.
I've read the output, using string output = proc.StandardOutput.ReadToEnd();
and I see that it contains the batch file content...
Can someone help me understand why it happens?
Thank you for your help :)
Here's the relevant code:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.CreateNoWindow = false;
proc.EnableRaisingEvents = false;
// the command
proc.StartInfo.FileName = command;
// the parameters of the command
proc.StartInfo.Arguments = args;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
try
{
// in case there is missing '"'
if (isContainQuote && index < 0)
{
str = "missing '\"' in the command " + commandStr;
}
else
{
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
if (bWaitForExit)
{
proc.WaitForExit(m_SHELL_CMD_TIMEOUT);
str = "Succeed to run the command: " + commandStr + ", Output: " + proc.StandardOutput.ReadToEnd();
}
else
{
str = "Succeed to run the command: " + commandStr;
}
}
}
catch (Exception e)
{
str = e.Message + ". Failed to run the command: " + commandStr;
// return the error from the operation system
}
Seeing your batch file could help. By default batch files echo their commands to standard out.
Try adding an #ECHO OFF command to the beginning of the batch file to be sure that the batch file commands aren't echoed to the standard output.
I am querying the version of sql server using sqlcmd (from my app) and would like to display the info, say, on a rich text box, how do i go about it, here's the code:
Process proc = new Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.FileName = "sqlcmd";
proc.StartInfo.Arguments = #"-U sa -P somepassword -q 'SELECT ##VERSION' -S (localhost)\InstanceName";
proc.Start();
StringBuilder q = new StringBuilder();
while (!proc.HasExited)
{
q.Append(proc.StandardOutput.ReadToEnd());
}
string r = q.ToString();
rtbCheckVersion.Text = r;
proc.WaitForExit();
since you have to execute a sql script, you could use SqlConnection and SqlCommand to get the output instead of starting a separated process.
check this answer and other answers in this question for some examples: https://stackoverflow.com/a/949933/559144
I see you don't want to use SqlConnection and SqlCommand...
I'm not sure, but it could be that your process exits before you get output.
Try this:
proc.Start();
string s = proc.StandardOutput.ReadToEnd();
I'm stuck trying to send commands to a cmd prompt that is waiting for my input.
The command in question is JavaLoader, which if I try to use on a BlackBerry device with a password it prompts me for a password. I would like to enter a password but using C# code.
Assuming that I've successfully created the cmd.exe using a Process like so:
process = new Process();
// Invokes the cmd process specifying the command to be executed.
string cmdProcess = string.Format(System.Globalization.CultureInfo.InvariantCulture, #"{0}\cmd.exe", new object[] { Environment.SystemDirectory });
// Pass executing file to cmd (Windows command interpreter) as a arguments
//Removed /C tells cmd that we want it to execute the command that follows, and then exit.
string cmdArguments = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}", new object[] { command });
// Pass any command line parameters for execution
if (arguments != null && arguments.Length > 0)
{
cmdArguments += string.Format(System.Globalization.CultureInfo.InvariantCulture, " {0}", new object[] { arguments, System.Globalization.CultureInfo.InvariantCulture });
}
process.StartInfo.FileName = cmdProcess;
process.StartInfo.Arguments = cmdArguments;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false; // Must be false for redirection
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
bool s = process.Start();
How do I go about responding the cmd's prompt for a passwords?
I've tried getting the Input stream and using .WriteLine("randompassword") like so:
while (process.Responding)
{
sw.WriteLine(response);
}
Another thing I've noticed is the prompt for a password is not being picked up as Output or Error and the application will in fact hang here because it's waiting for my input.
All I am trying to do is send a command that opens a model with the program.exe
Supposed to be super simple!
Ex:
"C:\Program Files (x86)\River Logic\Enterprise Optimizer 7.4 Developer\EO74.exe" "C:\PauloXLS\Constraint Sets_1.cor"
The line above works well if pasted on the command prompt window.
However, when trying to pass the same exact string on my code it gets stuck on C:\Program
string EXE = "\"" + #tbx_base_exe.Text.Trim() + "\"";
string Model = "\"" + #mdl_path.Trim()+ "\"";
string ExeModel = EXE + " " + Model;
MessageBox.Show(ExeModel);
ExecuteCommand(ExeModel);
ExeModel is showing te following line on Visual Studio:
"\"C:\\Program Files (x86)\\River Logic\\Enterprise Optimizer 7.4 Developer\\EO74.exe\" \"C:\\PauloXLS\\Constraint Sets_1.cor\""
To me looks like it is the string I need to send in to the following method:
public int ExecuteCommand(string Command)
{
int ExitCode;
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = true;
Process = Process.Start(ProcessInfo);
Process.WaitForExit();
ExitCode = Process.ExitCode;
Process.Close();
return ExitCode;
}
Things I've tried:
Pass only one command at a time (works as expected), but not an option since the model file will open with another version of the software.
Tried to Trim
Tried with # with \"
Can anyone see any obvious mistake? Thanks.
It's pretty straightforward. You just create a command line object then write to it, then to execute it you read back from it using SR.ReadToEnd():
private string GETCMD()
{
string tempGETCMD = null;
Process CMDprocess = new Process();
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo();
StartInfo.FileName = "cmd"; //starts cmd window
StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
StartInfo.CreateNoWindow = true;
StartInfo.RedirectStandardInput = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.UseShellExecute = false; //required to redirect
CMDprocess.StartInfo = StartInfo;
CMDprocess.Start();
System.IO.StreamReader SR = CMDprocess.StandardOutput;
System.IO.StreamWriter SW = CMDprocess.StandardInput;
SW.WriteLine("#echo on");
SW.WriteLine("cd\\"); //the command you wish to run.....
SW.WriteLine("cd C:\\Program Files");
//insert your other commands here
SW.WriteLine("exit"); //exits command prompt window
tempGETCMD = SR.ReadToEnd(); //returns results of the command window
SW.Close();
SR.Close();
return tempGETCMD;
}
Why are you opening a command prompt (cmd.exe)? Just pass the name of the executable.