How to execute command-line arguments with parameters in C#? - c#

I'm trying to compare two folders using a third party comparison tool called UltraCompare. The following line calls the program and opens two files... but this doesn't do anything except open them, plus it doesn't work properly for folders.
Process.Start("C:\\Program Files\\IDM Computer Solutions\\UltraCompare\\uc.exe",
textBoxContents1 + " " + textBoxContents2);
I'd like to use the following command line call which opens two folders, runs a comparison on them, and stores the results in output.txt: uc -d -dmf "c:\dir1" "c:\dir2" -o "c:\output.txt"
Also, I'd need to use variables for the folders instead of hardcoding the paths.
How can I work that into my C# code?
UPDATE 1:
I've modified my code according to your suggestions:
var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "C:\\Program Files\\IDM Computer Solutions\\UltraCompare\\uc.exe";
p.StartInfo.Arguments = String.Format("-d -dmf \"{0}\" \"{1}\" -o c:\\output2.txt",
textBoxContents1, textBoxContents2);
p.Start();
I'm wondering why the third line containing the arguments still doesn't work...
UPDATE 2:
My mistake. It is working now!! Just doesn't display the folders in UltraCompare but it is still writing and saving the output. Thanks guys!

You can use
yourProcess.StartInfo.Arguments = " .....";
Sample
var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "C:\\Program Files\\IDM Computer Solutions\\UltraCompare\\uc.exe";
p.StartInfo.Arguments = String.Format("-d -dmf {0} {1} -o c:\output.txt",textBoxContents1, textBoxContents2);
p.Start();

Process.Start(new ProcessStartInfo
{
FileName = #"C:\Program Files\IDM Computer Solutions\UltraCompare\uc.exe",
Arguments = String.Format("\"{0}\" \"{1}\"", textBoxContents1, textBoxContents2)
});

Make sure you use quotation marks for arguments, too!
If any of textBoxContents1 or textBoxContents2 contains spaces, you are busted!

Related

c# open cmd.exe process and Execute multiple commands

I would like to be able to open cmd and execute two commands from the window. First I would like to navigate to a particular directory where I can then run the second command from. Running a single command is pretty easy as this is all I have to do:
string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + #"\Cisco Systems\VPN Client\";
Process process = new Process();
ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", #"/c cd " + path );
process.StartInfo = processInfo;
process.Start();
However am not sure of the way to add the second argument so it runs after cmd runs the first command. Some research led me to this code snippet. Am unsure if this works since my aim is to start cisco vpn client from cmd and this seems not to start it. Here is the code:
string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + #"\Cisco Systems\VPN Client\";
Process process = new Process();
ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", #"/c cd " + path + "-t vpnclient connect user validuser pwd validpassword nocertpwd validconnectionentry ");
process.StartInfo = processInfo;
process.Start();
I once started the vpn client from cmd with the credentials just to make sure they were valid and it worked but I cant pull it off via C# programmatically.
Regards.
There three things you can do to achieve what you want. The easiest is to set the working directory of the process through ProcessStartInfo. This way you will only have to execute the command to start the VPN client.
The second option is redirecting the input and output of the process. (Also done through the ProcessStartInfo) This is something you want to do if you need to send more input to the process, or when you want to retrieve the output of the process you just started.
The third option is to combine the two commands with the & symbol. Using the & symbol makes cmd.exe execute the two commands sequentially (See here for an overview of the available symbols). Using this option will result in a command like this: /c cd path & vpnclient.
However because you just want to change the working directory of the process using the first option makes your code more readable. Because people reading your code do not need to know the & symbol in bash to understand what your code does. Changing the working directoy is done with the WorkingDirectory (MSDN) property of ProcessStartInfo (MSDN). See the following code:
var processInfo = new ProcessStartInfo("cmd.exe", #"/c vpnclient connect user validuser pwd validpassword nocertpwd validconnectionentry ");
processInfo.UseShellExecute = false;
processInfo.WorkingDirectory = path;
You can use & to execute next command or && to execute following command only if the previous one succeeded.
Examples:
dir /b & cls
and
taskkill /f /im explorer.exe && start explorer

Deleting directory that contains items

I am trying to delete a directory using C#. The first method I tried was
Directory.Delete(#"C:\Program Files (x86)\Qmuzki32");
I get an exception stating that the directory is not empty. I then found a cmd command which I can use to delete the directory quietly regardless of the fact that the directory is empty or not. I ran the following command in cmd:
rmdir /s /q "C:/Program Files (x86)/Qmuzik32"
This worked and did exactly what I wanted it to do. With my first attempt I tried building this command into a C# process like so:
if (Directory.Exists(#"C:\Program Files (x86)\Qmuzik32"))
{
string sQM32Folder = #"C:\Program Files (x86)\Qmuzik32";
Process del = new Process();
del.StartInfo.FileName = "cmd.exe";
del.StartInfo.Arguments = string.Format("rmdir /s /q \"{0}\"", sQM32Folder);
del.WaitForExit();
}
This did not work and then I tried it like this:
if (Directory.Exists(#"C:\Program Files (x86)\Qmuzik32"))
{
string sQM32Folder = #"C:\Program Files (x86)\Qmuzik32";
Process del = new Process();
del.StartInfo.FileName = "rmdir.exe";
del.StartInfo.Arguments = string.Format("/s /q \"{0}\"", sQM32Folder);
del.WaitForExit();
}
Same problem. I get the exception:
No process is associated with this object.
I do think I am on the right track; maybe the code above just requires some tweaking.
Just use Directory.Delete(string, bool).
While the low-level filesystem APIs of course require you to make sure the directory is empty first, any half-decent framework abstracting them allows you do do a recursive delete. In fact, existence of such a method would be the first thing I'd check before even trying to resort to external programs.
If you want to use the cmd way you can use this:
ProcessStartInfo Info = new ProcessStartInfo();
Info.Arguments = "/C rd /s /q \"C:\\Program Files (x86)\\Qmuzik32\"";
Info.WindowStyle = ProcessWindowStyle.Hidden;
Info.CreateNoWindow = true;
Info.FileName = "cmd.exe";
Process.Start(Info);
del.Start();
del.WaitForExit();
you didn't start the procces so it doesn't have a PID so it dies

How to use lame.exe in my application?

I capture audio files in the wave format in my Microsoft Surface application. Now for file size reasons, I'd like to convert the wave file into a mp3 file. I read in the Internet that a good possibility to do that is using lame.
But how can I call this exe file from my application? and how can I include it into my application?
Use Process class to call an external application:
string lameEXE = #"C:\path_of_lame\lame.exe";
string lameArgs = "-V2";
string wavFile = #"C:\my_wavs\input.wav";
string mp3File = #"C:\my_mp3s\output.mp3";
Process process = new Process();
process.StartInfo = new ProcessStartInfo();
process.StartInfo.FileName = lameEXE;
process.StartInfo.Arguments = string.Format(
"{0} {1} {2}",
lameArgs,
wavFile,
mp3File);
process.Start();
process.WaitForExit();
int exitCode = process.ExitCode;
You can call an executable from .NET by using the System.Diagnostics.Process class and related classes - see here for the documentation.
Lame has pretty robust command line arguments, which can be found here. You can pass command line arguments to the Process using the ProcessStartInfo.Arguments property.
public void mciConvertWavMP3(string fileName, bool waitFlag)
{
//maxLen is in ms (1000 = 1 second)
string outfile= "-b 32 --resample 22.05 -m m \"" + pworkingDir+fileName + "\" \"" + pworkingDir + fileName.Replace(".wav",".mp3") + "\"";
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
psi.FileName = "\"" + pworkingDir + "lame.exe" + "\"";
psi.Arguments = outfile;
//psi.WorkingDirectory = pworkingDir;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);
if (waitFlag)
{
p.WaitForExit();
// wait for exit of called application
}
}
Above code taken from here .
Depending on the usage, you can incorporate a Process.StartInfo object, control properties such as ShellExecute and also redirect any output from the application to (say) a log file or UI component.
To bundle the exe with your project, check this question from stackoverflow out. Personally, I'd go with the first suggestions:
There are several ways you could
accomplish this. First, you should add
program.exe to the project. You would
do this by right-clicking the project
in Visual Studio, and selecting Add >
Existing Item... Select program.exe,
and it will appear in the project.
Viewing its properties, you can set
"Copy to Output Directory" to "Copy
Always", and it will appear in your
output directory beside your
application.
If you stick to the above method, then reference lame.exe relatively ('....\Tools\Lame.exe' for example).
Finally, according to the official lame site : RareWares offers several compiled LAME versions, including modified versions featuring special functionality.
There is a DLL version of LAME, I would be surprised if you can't find a VB or C# example using it. Check this discussion thread: http://www.eggheadcafe.com/software/aspnet/31294459/-lameencdll-and-vbnet.aspx

How to send series of commands to a command window process?

We have a few commands(batch files/executables) on our network path which we have to call to initialize our 'development environment' for that command window. It sets some environmental variables, adds stuff to the Path etc. (Then only whatever working commands we type will be recognized & I don't know what goes inside those initializing commands)
Now my problem is, I want to call a series of those 'working commands' using a C# program, and certainly, they will work only if the initial setup is done. How can I do that? Currently, I'm creating a batch file by scratch from the program like this for example:
file.Writeline("InitializationStep1.bat")
file.Writeline("InitializeStep2.exe")
file.Writeline("InitializeStep3.exe")
Then the actual commands
file.Writeline("Dowork -arguments -flags -blah -blah")
file.Writeline("DoMoreWork -arguments -flags -blah -blah")
Then finally close the file writer, and run this batch file.
Now if I directly execute this using Process.<strike>Run</strike>Start("cmd.exe","Dowork -arguments"); it won't run.
How can I achieve this in a cleaner way, so that I have to run the initialization commands only once? (I could run cmd.exe each time with all three initializers, but they take a lot of time so I want to do it only once)
As #Hakeem has pointed out, System.Diagnostic.Process does not have a static Run method. I think you are referring to the method Start.
Once you have completed building the batch file, then simply execute it using the following code,
Process p = new Process();
p.StartInfo.FileName = batchFilePath;
p.StartInfo.Arguments = #"-a arg1 -b arg2";
p.Start();
Note that the # symbol is required to be prefixed to the argument string so that escape sequence characters like \ are treated as literals.
Alternative code
Process.Start(batchFilePath, #"-a arg1 -b arg2");
or
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.FileName = batchFilePath;
processStartInfo.Arguments = #"-a arg1 -b arg2";
Process.Start(processStartInfo);
More information
Process.Start method
Example of multi command batch file
dir /O
pause
dir
pause
Save this file as .bat and then execute using the Start method. In this case you can specify the argument with the command in the batch file itself (in the above example, the /O option is specified for the dir command.
I suppose you already have done the batch file creation part, now just append the arguments to the commands in the batch file.
Redirecting Input to a process
Since you want to send multiple commands to the same cmd process, you can redirect the standard input of the process to the take the input from your program rather than the keyboard.
Code is inspired from a similar question at: Execute multiple command lines with the same process using C#
private string ProcessRunner()
{
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.UseShellExecute = false;
Process process = Process.Start(processStartInfo);
if (process != null)
{
process.StandardInput.WriteLine("dir");
process.StandardInput.WriteLine("mkdir testDir");
process.StandardInput.WriteLine("echo hello");
//process.StandardInput.WriteLine("yourCommand.exe arg1 arg2");
process.StandardInput.Close(); // line added to stop process from hanging on ReadToEnd()
string outputString = process.StandardOutput.ReadToEnd();
return outputString;
}
return string.Empty;
}
The method returns the output of the command execution. In a similar fashion, you could also redirect and read the StandardOuput stream of the process.
The Process.Run method that you mentioned, is that from the Process class in System.Diagnostics namespace? AFAIK, the Process type doesn't have either a static or instance method named Run. If you haven't already I'd try with the Start method on Process, either instance or static

How can I pass more than one command line argument via c#

I need to pass more than one command line argument via c# for a process called handle.exe:
http://www.google.com.mt/search?sourceid=chrome&ie=UTF-8&q=handle.exe
First, I need to run the executable file via ADMINISTRATOR permissions. This post has helped me achieve just that:
programatically run cmd.exe as adminstrator in vista, c#
But then comes the next problem of calling the actual line arguments such as "-p explore"
How can I specify the command line arguments together, or maybe consecutively?
Current code is as follows:
Process p = new Process();
ProcessStartInfo processStartInfo = new ProcessStartInfo("filePath");
processStartInfo.CreateNoWindow = true;
processStartInfo.UseShellExecute = false;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.Verb = "runas";
processStartInfo.Arguments = "/env /user:" + "Administrator" + " cmd";
p.StartInfo = processStartInfo;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
Thanks
I believe the answer you are looking for is right out of the Runas command documentation.
runas /user:user#domain.microsoft.com "notepad my_file.txt"
It appears that the last argument to the runas command is the command that is being run along with any arguments. The key is to use quotes to group the actual command executable with it's arguments so that the values are not seen as separate arguments to the runas command but instead is issued as a single command on it's own.
So in your example you might want to do the following.
processStartInfo.Arguments = "/env /user:" + "Administrator" + " \"cmd -p explore\"";
You can run the process using the UseShellExecute command and pass in the username and password
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.useshellexecute%28v=VS.100%29.aspx
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.username%28v=VS.100%29.aspx
Although you will be storing the username and password somewhere.
If you are trying to run a process with elevated permissions, there may be a better way than calling runas.

Categories