command execution in C# - c#

I need to execute the following command, it works perfectly, if I execute it via command prompt, here the command line is using kodakprv.exe to send a print of a tiff file.
but when trying to execute it via c#, its not throwing any error but not sending the print either, tried to execute this command via xp_cmdshell in SQL, but it didn't work, in the xp_cmdshell documentation found that, quotes are not allowed for more then once, but kodakprv.exe print logic requires 3 pair of quotes
Please suggest can we use multiple quotes in C# while executing the command or suggest any better solution for it
String sCommand = "\"c:\\progra~1\\imagin~1\\kodakprv.Exe\" /pt \"D:\\SQLDev\\Dlls\\Testing.TIF\" \"\\\\Galactica\\C-Test1\"";
// Put your code here
System.Diagnostics.Process ExecuteCommand = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.Arguments = #" /c " + sCommand.ToString();
MessageBox.Show(startInfo.Arguments);
ExecuteCommand.StartInfo = startInfo;
ExecuteCommand.Start();

You don't need all those quotes. Only paths with spaces require quotes. None of your paths have spaces.
Shortnames, as you are using, may not exist (they can be turned off), or may not have the name you think. Windows does not preserve short names, only long names.
You are running your program via CMD. Unless your command line has redirection characters (as CMD handles redirection characters) then CMD is not required. You can start your program directly, which would be the preferred way (faster, less resources used).
Your window is set to hidden. Therefore you cannot see the message it is telling you. Unhide your window.
Your program will likely exit and close the window before you can read it. Either stick a &pause at the end of the command line sent to CMD, or read what is on both StdErr and StdOut as you specify to capture them in your code.

Related

Create new PowerShell process with pipes

Running this from CMD produces the correct result:
powershell -command "& Get-DiskImage -imagepath C:\\file.vhdx | Get-Disk"
<Here is some stuff regarding VHD>
I want to achieve exactly the same running this from C# (there's no way to run it directly, use some PowerShell related .NET stuff, or something else).
My code is the following:
static void LaunchCommandLineApp()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "powershell";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.RedirectStandardOutput = true;
startInfo.Arguments = "-command \" & get-diskimage -imagepath C:\\file.vhdx | Get-Disk \"";
using (Process exeProcess = Process.Start(startInfo)) {
exeProcess.WaitForExit();
var out = exeProcess.StandardOutput.ReadToEnd();
}
}
And in "out" I am getting an error:
Get-Disk : Cannot validate argument on parameter 'Number'. The argument is null. Provide a valid value for the argument, and then try running the command again.
But exactly the same code works in CMD. If I remove "| Get-Disk" from arguments, I will get correct output in "out" from the Get-DiskImage cmdlet.
Also, I have tried to play with curly braces, as other answers suggested - error haven't changed.
What shall I put in "startInfo.Arguments", so my output of "Get-DiskImage" will be correctly piped to the next cmdlet?
This is not actually a problem with the difference between running from the command line and from C#. I created a test VHDX and got the same (error) result whether run from C# or the command line, as shown by the OP.
In both cases, omitting the | Get-Disk part showed information about the disk image, which lacked a disk number, which is exactly what Get-Disk was complaining about. I suspect the image needs to be mounted for it to have a disk number.

My command which is being produced by my C# code isn't working in C#, but works perfectly when I paste it to cmd

It's all about a line I want to use to get windows update information, which is part of wmic.
My code looks like this:
Process p = new Process();
string arguments = "qfe list full /format:htable > "+ path;
ProcessStartInfo procStartInfo = new ProcessStartInfo("wmic", arguments);
procStartInfo.CreateNoWindow = true;
procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
procStartInfo.UseShellExecute = false;
p.StartInfo = procStartInfo;
p.Start();
while path is the valid location where the file would be dumped, ending with a hotfixlog.htm of course.
The problem is, that nothing happens at all. However, when I take the final product from the arguments-variable, and paste it manually into cmd with 'wmic < variablecontent >' it's working perfectly fine and I end up with the .htm I expect.
The line created looks like this:
"qfe list full /format:htable > C:\Users\...\WindowsHotfixes.htm"
What do I have to change to make it work from the code? I was expecting the backslashes to cause problems, but when manually entering the line they don't.
Your code will not work because the redirection operator (>) is not an element of the OS available to any application, but an operator in cmd.exe. It works in the command line because cmd is handling it, but wmic doesn't know what to do with it.
You can use the redirection if your command line is something like
cmd /c"wmic qfe list full /format:htable > x:\somewhere\file.htm"
Or you can remove the redirection and indicate to wmic that you want the data saved in a file
wmic /output:"x:\somewhere\file.htm" qfe list full /format:htable

Writing and executing multiple lines sequentially in an elevated command prompt using c#

Am a Newbie in C# and I have 3 commands(command2, command3 and command4) I need to execute in the elevated command prompt and I will also like to view the execution process as it happens. Currently, the problem is that the code below just opens the elevated command prompt and without executing the commands. I also seek better interpretations of the lines if wrong.
My code and Interpretation/Understanding of each line based on reviews of similar cases: ConsoleApp1
class Program
{
static void Main(string[] args)
{
string command2 = #"netsh wlan";
string command3 = #" set hostednetwork mode=true ssid=egghead key=beanhead keyusage=persistent";
string command4 = #" start hostednetwork";
string maincomm = command2.Replace(#"\", #"\\") + " " + command3.Replace(#"\", #"\\") ; //I merged commands 2 and 3
ProcessStartInfo newstartInfo = new ProcessStartInfo();
newstartInfo.FileName = "cmd"; //Intend to open cmd. without this the newProcess hits an error saying - Cannot run process without a filename.
newstartInfo.Verb = "runas"; //Opens cmd in elevated mode
newstartInfo.Arguments = maincomm; //I intend to pass in the merged commands.
newstartInfo.UseShellExecute = true; //
newstartInfo.CreateNoWindow = true; // I intend to see the cmd window
Process newProcess = new Process(); //
newProcess.StartInfo = newstartInfo; //Assigns my newstartInfo to the process object that will execute
newProcess.Start(); // Begin process and Execute newstartInfo
newProcess.StartInfo.Arguments = command4; //I intend to overwrite the initial command argument hereby passing the another command to execute.
newProcess.WaitForExit(); //
}
}
This is what I did to overcome the challenge and It gave me exactly what I wanted. I modified my code to use the System.IO to write directly to the elevated command prompt.
ProcessStartInfo newstartInfo = new ProcessStartInfo();
newstartInfo.FileName = "cmd";
newstartInfo.Verb = "runas";
newstartInfo.RedirectStandardInput = true;
newstartInfo.UseShellExecute = false; //The Process object must have the UseShellExecute property set to false in order to redirect IO streams.
Process newProcess = new Process();
newProcess.StartInfo = newstartInfo;
newProcess.Start();
StreamWriter write = newProcess.StandardInput ; //Using the Streamwriter to write to the elevated command prompt.
write.WriteLine(maincomm); //First command executes in elevated command prompt
write.WriteLine(command4); //Second command executes and Everything works fine
newProcess.WaitForExit();
Referrence: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardinput(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo(v=vs.110).aspx
I think an understanding of some properties of the ProcessStartInfo might clear things.
The verb - Gets or sets the verb to use when opening the application or document specified by the FileName property.,
+The UseShellExecute - Gets or sets a value indicating whether to use the operating system shell to start the process.
+The FileName - Gets or sets the application or document to start MSDN Docs
When you use the operating system shell to start processes, you can start any document (which is any registered file type associated with an executable that has a default open action) and perform operations on the file, such as printing, by using the Process object. When UseShellExecute is false, you can start only executables by using the Process object Documentation from MSDN.
In my case, cmd is an executable. the verb property is some thing that answers the question "How should my I run my FileName(for executables e.g cmd or any application)?" for which I answered - "runas" i.e run as administrator. When the FileName is a document (e.g `someFile.txt), the verb answers the question "What should I do with the file for which answer(verb) could be -"Edit","print" etc. also?"
use true if the shell should be used when starting the process; false if the process should be created directly from the executable file. The default is true MSDN Docs - UserShellInfo.
Another thing worth noting is knowing what you are trying to achieve. In my case, I want to be able to run commands via an executable(cmd prompt) with the same process - i.e starting the cmd as a process I can keep track of.

Compile an .asm file through c# using cmd

I want to compile an .asm file placed in bin folder in the masm through c#.I have tried multiple methods like process.start but nothing helps.It opens the cmd but the command "ml" never executes.It either open the pwb.exe(MASM) or the 'file.asm' in notepad.I give these arguments to CMD "path\ml file.asm" which works fine manually.ml is a command used to compile .asm files. One of the method I used is following
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = #"C:\WINDOWS\system32\cmd.exe";
startInfo.Arguments = "C:\Users\Hassan\Documents\Visual Studio 2010\Projects\FYP\FYP\MASM611\BIN\ml file.asm";
process.StartInfo = startInfo;
process.Start();
If you want to start the process in this way, you'll need to put quotes round the path, due to the spaces:
startInfo.Arguments = #"""C:\Users\Hassan\Documents\Visual Studio 2010\Projects\FYP\FYP\MASM611\BIN\ml"" file.asm";
(In a verbatim string literal, you include double-quotes by doubling them.)
Alternatively, if ml is actually an executable (I know nothing about masm) you could just use:
startInfo.FileName = #"C:\Users\Hassan\Documents\Visual Studio 2010\Projects\FYP\FYP\MASM611\BIN\ml.exe";
startInfo.Arguments = "file.asm";
To start "cmd.exe" and run another program you need to use the /c switch.
/C Carries out the command specified by string and then terminates
So you would need:
startInfo.Arguments = "/c \"C:\Users\Hassan\Documents\Visual Studio 2010\Projects\FYP\FYP\MASM611\BIN\ml.exe\" file.asm";
I've added extra quotes for the space in the path.
If you don't need to run it via the command prompt - "cmd.exe" - then you can put the path to "ml.exe" in FileName and just pass the "file.ml" as the Arguments.

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

Categories