cmd.exe and adb command - c#

Hello I have some issue with cmd command via c#
for example I do manually commands in cmd.exe
//command1 to pick directory
cd C:\Users\NewSystem\source\repos
//command2 command to send file to emulator
adb -s emulator-5554 push Debug\funnels\01\01.mp4 /sdcard/Download
code I test in C# is and it doesnt work properly, exactly not send nothing to android emulator
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WorkingDirectory = #"C:\Users\NewSystem\source\repos\";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = false;
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("adb -s emulator-5554 push Debug\funnels\01\01.mp4 /sdcard/Download");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();

To start cmd.exe and have it execute a command you need to pass /c (execute command and exit) or /k (execute command and remain)...
cmd /c adb -s emulator-5554 push Debug\funnels\01\01.mp4 /sdcard/Download
You don't need to have cmd.exe start adb.exe, though; just start adb.exe directly.
As for your C# code, StandardInput is for writing to a process's stdin stream, which is not what you want. The way to pass command line arguments is using the ArgumentList (.NET (Core) 2.1+) or Arguments (all .NET Framework/Core versions) properties of ProcessStartInfo...
// Dispose cmd when finished
using (Process cmd = new Process())
{
// The full executable path is required if its directory is not in %PATH%
cmd.StartInfo.FileName = #"C:\Users\NewSystem\source\repos\adb.exe";
cmd.StartInfo.Arguments = #"-s emulator-5554 push ""Debug\funnels\01\01.mp4"" ""/sdcard/Download""";
cmd.StartInfo.WorkingDirectory = #"C:\Users\NewSystem\source\repos\";
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.WaitForExit();
}
I set Arguments to a verbatim string with the last two arguments quoted just to show how you would do so if either path contain spaces.

Related

Command Line outputs does not show up

I wrote an MP3 conversion application which uses the ffmpeg encoder executable. When I just send the -h (help) argument to it, I can get all of the outputs to my txt file. But when I try to send the actual conversion arguments, the command works as expected but I can not get the output lines.
Here is my snippet:
/* Success */
string ffmpeg_cmd = "ffmpeg -h";
/* Below command works well, but it's not able to get the output */
//string ffmpeg_cmd = "ffmpeg -i inputFile.wav -vn -ar 44100 -ac 2 -ab 320k -f mp3 -y outputFile.mp3";
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine(ffmpeg_cmd /* + " & exit" */); //"ping bing.com"
string output = cmd.StandardOutput.ReadToEnd();
File.AppendAllText(Directory.GetCurrentDirectory() + #"\cmd_logs.txt", output );
cmd.WaitForExit();
As I said, both command work as expected. The problem is only the second one can not get the output.
Try this:
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = "/c ffmpeg.exe -i REMINDER.WAV -vn -ar 44100 -ac 2 -ab 320k -f mp3 -y REMINDER.mp3 2>>cmd_logs.txt";
cmd.Start();
cmd.WaitForExit();
Edit::
You may also use -report option to generate log of ffmpeg.exe
Update:
ffmpeg uses StandardOutput to create binary output file. In your case MP3. For logs, it use StandardError stream. You can make your code working by making RedirectStandardError = true and by reading cmd.StandardError.ReadToEnd().
One more thing. you can use cmd.StartInfo.Arguments option to pass parameters instead of using input redirection. And if you are calling it through CMD, use /c option too. Otherwise command window will not be terminated automatically.

multiple command one by one in cmd.exe via c#

I trying to run the following command in cmd.exe by c# code.
mkdir myfolder
cd myfolder
git init
git remote set-url origin https://gitlab.company.com/testgroup/server.git
git fetch --dry-run
cd ..
rmdir myfolder
I don't know how to pass all the arguments in single Process.Start();. After run the 4th command I will take the output string and do some operation with that string.
I tried like this
const string strCmdText = "/C mkdir myfolder& cd myfolder& git init & git remote set-url origin https://gitlab.company.com/project.git & git fetch --dry-run & cd .. & rmdir myfolder";
Process.Start("CMD.exe", strCmdText);
Above command works properly. But I do not know how to get the execution text from cmd.exe. The text which I want is shown in below image.
I used below code to get the output string. But at the line of reading the output(string output = cmd.StandardOutput.ReadToEnd();), the execution stopped. I means it will not go to next line also it will not terminate the program. Simply show the lack screen.
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.Arguments = "/C mkdir myfolder& cd myfolder& git init & git remote set-url origin https://gitlab.company.com/project.git & git fetch --dry-run & cd .. & rmdir myfolder";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardError = true;
cmd.Start();
string output = cmd.StandardOutput.ReadToEnd();
Console.WriteLine(output);
How do I get the output string?
If you use 'ReadToEnd', you will wait for end of stream. You should use 'Read' or 'ReadLine' for reading parts of available stream context:
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.Arguments = "/C mkdir myfolder& cd myfolder& git init & git remote set-url origin https://gitlab.company.com/project.git & git fetch --dry-run & cd .. & rmdir myfolder";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardError = true;
cmd.Start();
while (!cmd.StandardOutput.EndOfStream) {
string line = cmd.StandardOutput.ReadLine();
Console.WriteLine(line);
}

How to run a mysqlcheck through c#

I'm currently trying to do a basic mysqlcheck through the command prompt. The mysql.exe file itself is within a bin that the working directory is pointing towards to use as part of the commands though the cmd.
Right now I'm getting stuck to where it is stopping while opening the shell. It doesn't proceed to initiate the standardinput.
{
Process proc = new Process();
proc.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");
proc.StartInfo.WorkingDirectory = #"C:\Program Files (x86)\MySQL\bin";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.Arguments = #"Mysqlcheck -u root -c -ppassword database";
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
proc.StandardInput.WriteLine("Mysqlcheck -u root -c -ppassword database");
proc.WaitForExit();
}
Add the /C option before the name of the executable
proc.StartInfo.Arguments = #"/C Mysqlcheck.exe -u root -c -ppassword database";
Without this argument the cmd shell doesn't execute the command but exits immediately.
You can see other arguments for the CMD.exe opening a command prompt and typing CMD /?

Excute a command in the cmd from c#

I want to run multiple CMD command from C# application.
The command on the cmd is like that "C:\Users\Sara Mamdouh\Desktop\New folder> hvite -T 01 -C hcon.con -w net dict hmm_list Ann.wav".
My question is how to call this command from the C# application and also receive the results in a string?
First of all, you should write this in a bat file and save it as a like bat.bat.
cd \
cd C:\Users\Sara Mamdouh\Desktop\New folder
exit
You can use Process.Start() method after that.
Starts a process resource by specifying the name of an application and
a set of command-line arguments, and associates the resource with a
new Process component.
Process p = new Process();
ProcessStartInfo ps = new ProcessStartInfo();
ps.FileName = "path to bat.bat";
ps.RedirectStandardInput = true;
ps.RedirectStandardOutput = true;
ps.UseShellExecute = false;
p.StartInfo.Arguments = "hvite -T 01 -C hcon.con -w net dict hmm_list Ann.wav";
p.StartInfo = ps;
p.Start();
string output = p.StandardOutput.ReadToEnd();
var cmd = #"hvite -T 01 -C hcon.con -w net dict hmm_list Ann.wav";
System.Diagnostics.Process.Start("CMD.exe", cmd);
You can use the Process.Start method if you just need to start a process:
System.Diagnostics.Process.Start("cmd" "whatever parameters");
For reading the output, look at the examples on the MSDN page for Process.StandardOutput:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
Basically, instead of just calling Process.Start, you create a new Process object with the required parameters, call Start() on it and then read the output as in the example.
Read the documentation for the Process class.
As the informative output C:\Users\Sara Mamdouh\Desktop\New folder> you see in the console window may not be part of the command you're issuing, you need to add the absolute path names to the command, so the files can be found:
var cmd = #"\"<path to hvite>\hvite\" -T 01 -C hcon.con -w net dict hmm_list \"C:\Users\Sara Mamdouh\Desktop\New folder\Ann.wav\"";
System.Diagnostics.Process.Start("CMD.exe", cmd);

Running multiple commands in a command line utility using cmd.exe from .Net win form

I want to run tabcmd.exe utility to publish views in tableau server. Manual step to do this is as follows, log file will be updated for every step in the location
"C:\Users[UserName]\AppData\Roaming\Tableau\tabcmd.log"
In the same session I have to perform this steps manually one by one order
Run cmd.exe
log in by using the command tabcmd login -s "http:/sales-server:8000" -t Sales -u administrator -p p#ssw0rd!
Create Project Name using the command tabcmd createproject -n "Quarterly_Reports" -d "Workbooks showing quarterly sales reports."
Publish views by using the command tabcmd publish "analysis.twbx" -n "Sales_Analysis" --db-user "jsmith" --db-password "p#ssw0rd"
Refresh by using the command tabcmd refreshextracts --workbook "My Workbook"
Log out by using the command tabcmd logout
Now I am trying to automate this steps from my .Net win form, so I used below code as a try and It is not working.
String path = #"C:\Program Files (x86)\Tableau\Tableau Server\7.0\bin\tabcmd.exe"
ProcessStartInfo startInfo = new ProcessStartInfo ();
startInfo.FileName = "\""+path+ "\"";
startInfo.Arguments = String.Format("login -s http://Server1:8000 --db-user "jsmith" --db-password "p#ssw0rd");
startInfo.UseShellExecute = false ;
startInfo.CreateNoWindow = false;
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardError = true;
Process p = new Process();
p.StartInfo = startInfo;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("createproject -n \"MyProject\" -d \"MyProjectWorkbook\"");
//sw.WriteLine("My next Command");
//sw.WriteLine("My next Command");
}
}
I am able to log in successfully and I am not able to proceed consequent steps further, I have no clue how to proceed on this further, so I am looking forward some help on this.
Thanks in advance!
I'm unsure if this is of use to you or not but you could try creating a batch file with all of those commands and the execute the batch file from command prompt like this :-
//Build Commands - You may have to play with the syntax
string[] cmdBuilder = new string[5]
{
#"tabcmd login -s 'http:/sales-server:8000' -t Sales -u administrator -p p#ssw0rd!",
#"tabcmd createproject -n 'Quarterly_Reports' -d 'Workbooks showing quarterly sales reports.'",
#"abcmd publish 'analysis.twbx' -n 'Sales_Analysis' --db-user 'jsmith' --db-password 'p#ssw0rd'",
#"tabcmd refreshextracts workbook 'My Workbook'",
#"tabcmd logout"
};
//Create a File Path
string BatFile = #"\YourLocation\tabcmd.bat";
//Create Stream to write to file.
StreamWriter sWriter = new StreamWriter(BatFile);
foreach (string cmd in cmdBuilder)
{
sWriter.WriteLine(cmd);
}
sWriter.Close();
//Run your Batch File & Remove it when finished.
Process p = new Process();
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "C:\\cmd.exe";
p.StartInfo.Arguments = #"\YourLocation\tabcmd.bat";
p.Start();
p.WaitForExit();
File.Delete(#"\YourLocation\tabcmd.bat")
I'll leave the output section to yourself. You could try this, it is not exactly clean but will automate the main steps. It's either this, or opening a process for each command as the last process exits?
Hope this is of help.

Categories