I'm working on a project where you "send" a command to the cmd.exe and receive the output. For this command you need a file path -k and an url.
I have the following code (names and values changed):
string path = "C:\Users\program.exe"
string pathcustom = "\"" + path + "\""; //the path needs to be in quotation marks
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
string Address = "1.2.3"
string command = pathcustom + " " + "-k" + " " + "https://username:passwort#serveradress" + Address; //Serveradress is the URL
p.StartInfo.Arguments = "/C " + command;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string ReturnValue = p.StandardOutput.ReadToEnd();
This Code is working fine like I want it to be, but I need another methode thats exactly similar except that the Address looks different. In the code above it would look something like 1.2.3 but int the following method the Address has to look like this (including the backslashes and quotation marks) \"ab:cd:de\" so let's pretend this is
string path = "C:\Users\program.exe"
string pathcustom = "\"" + path + "\"";
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
string Address = #"\""ab:cd:de\""";
string command = pathcustom + " " + "-k" + " " + "https://username:passwort#serveradress" + Address;
p.StartInfo.Arguments = "/C " + command;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string ReturnValue = p.StandardOutput.ReadToEnd();
When I rewrite the code so that the cmd stays open, with the first method I get the ouput I want/expect. But with the second, not working, method, it sends the command to the cmd and executes it, but it writes as "message" that the command was either written wrong or it couldn't be found. But when i take exactly the same code (via streamwriter I write the command for the cmd into a textfile) and copy it into the cmd, it executes it like it should. So basically, it just doesn't work if I execute the command via c#. Please help
You have to wait for the application to exit
Use something like p.WaitForExit(milliseconds)
Or check p.HasExited
According to this MSDN Post, in order for an argument in StartInfo.Arguments to keep the quotes, you need to "triple escape it" , like this:
string Address = "\\\"\"\"ab:cd:de\\\"\"\";
string command = pathcustom + " " + "-k" + "https://username:passwort#serveradress" + Address;
Related
I am trying to run the findstr command from C# (Windows Forms).
I have tried this normally in Command Prompt it works fine.
string CD = #"P:\FIles";
Process p = new Process();
p.StartInfo = new ProcessStartInfo("findstr.exe");
p.StartInfo.Arguments = "-M -S" + " " + quote + txtSearch.Text + quote + " " + quote+"dummy.txt"+quote + " > " + "C:\\Temp\\results.txt" ;
p.StartInfo.WorkingDirectory = CD;
p.StartInfo.ErrorDialog = true;
p.StartInfo.UseShellExecute = false;
p.Start();
p.WaitForExit();
I would like to save the output to another text file with a specific location.
It would be even better if I could somehow return the result directly back to the form it self and maybe copy each line to a list box.
You can read the output of a console application with reading the "StandardOutput" stream. But you have to set the StartInfo.RedirectStandardOutput property to "true" before.
In your case:
string CD = #"P:\FIles";
Process p = new Process();
p.StartInfo = new ProcessStartInfo("findstr.exe");
p.StartInfo.Arguments = "-M -S" + " " + quote + txtSearch.Text + quote + " " + quote+"dummy.txt"+quote + " > " + "C:\\Temp\\results.txt" ;
p.StartInfo.WorkingDirectory = CD;
p.StartInfo.ErrorDialog = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
p.WaitForExit();
string sTest = p.StandardOutput.ReadToEnd();
I've been trying all day to start process which would run the following code:
C:\bin\ant.bat -f=C:\build.xml -DinputFile=C:\Desktop\Book1.xml -DstartDate=2018-06-20 -DxslFile=ProcessingDate -DoutputFile=fff
and it works completely fine in cmd.
this is my last code in C# which I really hoped would work, but however it doesn't:
public void run() {
string antFile = #"C:\ant.bat";
string build = #"C:\build.xml";
string inputFile = #"C:\Book1.xml";
string startDate = "2018-05-23";
string outputFile = "ff";
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd.exe", "/c" + #"C:bin\ant.bat -f=C:\build.xml -DinputFile=C:\Desktop\Book1.xml -DstartDate=2018-06-20 -DxslFile=ProcessingDate -DoutputFile=test0.xsl");
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
ProcessStartInfo procStartInfo2 = new ProcessStartInfo("cmd.exe", "/c" + antFile + "-f=" + build + "-DinputFile=" + inputFile + "-DstartDate=" + startDate + "-DxslFile=" + startDate + "-DoutputFile=" + outputFile);
Process proc2 = new Process();
proc2.StartInfo = procStartInfo2;
proc2.Start();
}
Firstly, I've tried to just put everything from cmd to the process but it didn't work, after I tried to do what I actually have to: put all the string values as arguments but it didn't work either.
Instead I am getting bunch of exceptions
I'm literally out of options as I've sat all day doing this. Does anyone have idea what problem it could be?
UPDATE:
I've managed to run startInfo3 process. But startInfo4 still doesn't work. I've checked both lines seem to produce the same so what's wrong with it if they're are the same. Do I pass them incorrectly?
ProcessStartInfo startInfo3 = new ProcessStartInfo();
startInfo3.FileName = "cmd.exe";
startInfo3.Arguments = "/c" + #"C:\ant.bat -f=C:\build.xml -DinputFile=C:\Book1.xml -DstartDate=2018-06-20 -DxslFile=ProcessingDate -DoutputFile=fff";
Process.Start(startInfo3);
ProcessStartInfo startInfo4 = new ProcessStartInfo();
startInfo4.FileName = "cmd.exe";
startInfo4.Arguments = "/c" + antFile + "-f=" + build + "-DinputFile=" + inputFile + "-DstartDate=" + startDate + "-DxslFile=" + startDate + "-DoutputFile=" + outputFile;
Process.Start(startInfo4);
After digging a bit more I figured out an answer:
ProcessStartInfo procStartInfo5 = new ProcessStartInfo();
procStartInfo5.FileName = "cmd.exe";
procStartInfo5.Arguments = $"/c{antFile} -f={build} -DinputFile={inputFile} -DstartDate={startDate} -DxslFile=ProcessingDate -DoutputFile={outputFile}";
Process.Start(procStartInfo5);
Hope it helps someone!
I need help with my application, I created an application that when they hit the update button will execute some PsExec file to remotetly run some functions. the problem comes that works good in my machine locally but my application will be shared to a lot of users. and I don't want to install to all users the PsExec file to their computers, I just want my program to be installed in their computers and just run the program without any issues.
My code works all the application I just need to add that piece of code that will make the program call the PsExec without knowing the whole Path, right now I installed the PsExec file to my Debug folder, which is the folder that is in my project.
So instead of using the whole PsExec path that is on my directory i will like to use the one of my project
I don't want to use this
string leMars21StArguments = #"/C C:\PowerShellRemotly\PsExec.exe " +
#"-i \\VML-2012-QBOOK2 -u mydomain\" + userInfo.Username + " -p " +
userInfo.Password + " -d C:\\batch\\myfile.bat";
I would like something like this where the debug folder of the project, but it doesn't work. is there another to do this?
string leMars21StArguments = #"/C Debug\PsExec.exe " +
#"-i \\VML-2012-QBOOK2 -u mydomain\" + userInfo.Username + " -p " +
userInfo.Password + " -d C:\\batch\\myfile.bat";
Here's the full code:
Process p = new Process();
//assigned from the form txtboxes to the UserInformation class
userInfo.Username = txt_Username.Text;
userInfo.Password = txt_Password.Text;
//string variabes for the cmd arguments
string leMars21StArguments = #"/C C:\PowerShellRemotly\PsExec.exe -i " +
#"\\VML-2012-QBOOK2 -u mydomain\" + userInfo.Username + " -p " +
userInfo.Password + " -d C:\\batch\\myfile.bat";
if (userInfo.Username == string.Empty)
{
MessageBox.Show("Username cannot be null, please try again");
}
if (userInfo.Password == string.Empty)
{
MessageBox.Show("Password cannot be null, please try again");
}
if (cmb_DatabaseSelection.SelectedItem == "location")
{
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.Arguments = leMars21StArguments;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
string errOutput = p.StandardError.ReadToEnd();
p.Close();
MessageBox.Show(errOutput);
}
If you add it to your program, then you can just reference the location relative to your .exe where you place it.
For example, if you add a new folder called "Tools" to your project, and then add psexec.exe there, and set it to "Copy if newer" (or "Copy always"):
Then you can always get the path to it by grabbing the directory that your .exe is in and navigating to the "Tools" folder (note that you will need a reference to System.Reflection to use Assembly.GetExecutingAssembly):
var thisExeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var psExecPath = Path.Combine(thisExeDirectory, "Tools", "psexec.exe");
As an example:
var userInfo = new UserInfo {Password = "LetMeIn", Username = "rufusl"};
var thisExeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var psExePath = Path.Combine(thisExeDirectory, "Tools", "psexec.exe");
var leMars21StArguments =
"/C \"" + psExePath + #""" -i \\VML-2012-QBOOK2 -u mydomain\" + userInfo.Username +
" -p " + userInfo.Password + #" -d C:\batch\myfile.bat";
Console.WriteLine(leMars21StArguments);
Output
UPDATED...
I want to call kdiff from Console application. So I'm building two files and want to compare they at the end of executing my program:
string diffCmd = string.Format("{0} {1}", Logging.FileNames[0], Logging.FileNames[1]);
// diffCmd = D:\vdenisenko\DbHelper\DbHelper\bin\Debug\Reports\16_Nov 06_30_46_DiscussionThreads_ORIGIN.txt D:\vdenisenko\DbHelper\DbHelper\bin\Debug\Reports\16_Nov 06_30_46_DiscussionThreads_ORIGIN.txt
System.Diagnostics.Process.Start(#"C:\Program Files (x86)\KDiff3\kdiff3.exe", diffCmd);
//specification is here http://kdiff3.sourceforge.net/doc/documentation.html
It runs kdiff3 tool, but something wrong with filenames or command... Could you please look on screenshot and say what is wrong?
You need to use Process.Start():
string kdiffPath = #"c:\Program Files\Kdiff3.exe"; // here is full path to kdiff utility
string fileName = #"d:\file1.txt";
string fileName2 = #"d:\file2.txt";
Process.Start(kdiffPath,String.Format("\"{0}\" \"{1}\"",fileName,fileName2));
Arguments as described in the docs: kdiff3 file1 file2
var args = String.Format("{0} {1}", fileName, fileName2);
Process.Start(kdiffPath, args);
string kdiffPath = #"c:\Program Files\Kdiff3.exe"; // here is full path to kdiff utility
string fileName = #"d:\file1.txt";
string fileName2 = #"d:\file2.txt";
ProcessStartInfo psi = new ProcessStartInfo(kdiffPath);
psi.RedirectStandardOutput = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.Arguments = fileName + " " + fileName2;
Process app = Process.Start(psi);
StreamReader reader = app.StandardOutput;
//get reponse from console app in your app
do
{
string line = reader.ReadLine();
}
while(!reader.EndOfStream);
app.WaitForExit();
This will run the program from your console app
Process p = new Process();
p.StartInfo.FileName = kdiffPath;
p.StartInfo.Arguments = "\"" + fileName + "\" \"" + fileName2 + "\"";
p.Start();
Unless you are trying to do something else, in which case you need to provide more details.
I wrote the code to convert the file in c#asp.net using ffmpeg. While executing it shows error as "The filename, directory name, or volume label syntax is incorrect" but my paths are correct. So what is the solution for this?
ProcessStartInfo info = new ProcessStartInfo("e:\ffmpeg\bin\ffmpeg.exe", "-i cars1.flv -same_quant intermediate1.mpg");
process.Start();
I tried another way as shown below. But that is also won't works.
ProcessStartInfo info = new ProcessStartInfo("ffmpeg.exe", "-i cars1.flv -same_quant intermediate1.mpg");
Please help me with sample code for converting one video file format to another using ffmpeg in c# asp.net. Thanks in advance.
There is wrapper library available
http://www.ffmpeg-csharp.com/
Also refer
http://www.codeproject.com/Articles/24995/FFMPEG-using-ASP-NET
https://stackoverflow.com/questions/tagged/asp.net+c%23+video
string apppath = Request.PhysicalApplicationPath;
string outf = Server.MapPath(".");
string fileargs = "-i" + " " + "\"C:/file.mp4 \"" + " " + "\"C:/files/test.flv \"";
Process myProcess = new Process();
myProcess.StartInfo.FileName = Server.MapPath(".")+"//ffmpeg.exe";
myProcess.StartInfo.Arguments = fileargs;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.CreateNoWindow = false;
myProcess.StartInfo.RedirectStandardOutput = false;
myProcess.Start();
myProcess.WaitForExit(50 * 1000);
Thanks
Deepu
The backslashes (\) in your path are considered to start escape sequences. To prevent this, either use double backslashes (\\), or prefix the string with #.
ProcessStartInfo info = new ProcessStartInfo("e:\\ffmpeg\\bin\\ffmpeg.exe",
"-i cars1.flv -same_quant intermediate1.mpg");
Or:
ProcessStartInfo info = new ProcessStartInfo(#"e:\ffmpeg\bin\ffmpeg.exe",
"-i cars1.flv -same_quant intermediate1.mpg");
You need to have backslashes in your path see below this is how I create videos using ffmpeg.exe
string sConverterPath = #"C:\ffmpeg.exe";
string sConverterArguments = #" -i ";
sConverterArguments += "\"" + sAVIFile + "\"";
sConverterArguments += " -s " + iVideoWidth.ToString() + "x" + iVideoHeight.ToString() + " ";
sConverterArguments += " -b " + iVideoBitRate.ToString() + "k -ab " + iAudioBitRate.ToString() + "k -ac 1 -ar 44100 -r 24 -absf remove_extra ";
sConverterArguments += "\"" + sOutputFile + "\"";
Process oProcess = new Process();
oProcess.StartInfo.UseShellExecute = true;
oProcess.StartInfo.Arguments = sConverterArguments;
oProcess.StartInfo.FileName = sConverterPath;