How to run a specific DOS Command - c#

I tried various methods possible to run this specific DOS command through C#. I do not want to use a batch file. Whatever I try, it keeps taking only first word from Printer name and not the entire name, in this case, it says Printer POS is not connected instead of saying Printer POS Lexmark is not connected. What could the error be? Thanks guys!
The DOS command is:
rundll32 printui, PrintUIEntry /o /n "POS Lexmark"
My code is as follows:
string command = string.Format("/c rundll32 printui, PrintUIEntry /o /n" + " POS Lexmark");
ProcessStartInfo cmdsi = new ProcessStartInfo("cmd.exe");
cmdsi.Arguments = command;
cmdsi.CreateNoWindow = false;
Process cmd = Process.Start(cmdsi);

You forgot to include the quotes around POS Lexmark:
string command = string.Format("/c rundll32 printui, PrintUIEntry /o /n" + "\" POS Lexmark\"");

Related

how to execute a terminal command in c#

I read many post, from them there is this one
c# - Opening the terminal process and pass commands?
I do the exact same thing in my code
Process proc = new System.Diagnostics.Process ();
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c \" " + command + " \"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start ();
where command = export DISPLAY=:0.0
and it goes to my catch, "pplicationName='/bin/bash', CommandLine='-c " cd .. "', CurrentDirectory='', Native error= The system cannot find the file specified."
what do I do differently? even if I try to juste set command = "cd .." it doesn't work
You should probably try setting the full path the executable.
proc.StartInfo.FileName = "C:/SOMEPATH/Bash.exe";
I'm assuming as you are specifying a relative path, it's not resolving it. Possibly because you aren't setting a working directory for the process so it's current dir and the current dir you think it has, are different.

How to pause cmd before it close?

This is my code
System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo();
proc.FileName = #"cmd.exe";
proc.Arguments = "/C "+ "ipconfig" ;
System.Diagnostics.Process.Start(proc);
when I run this code , Cmd run and shut down so quickly .
How to pause it ?
THANKS A LOT :)
Specify the K parameter instead of C
From Microsoft documentation:
/c : Carries out the command specified by string and then stops.
/k : Carries out the command specified by string and continues.
proc.Arguments = "/K "+ "ipconfig" ;
more info: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true
Use /K instead of /C.
proc.Arguments = "/K " + "ipconfig";
You can see a list of command line switches here
/C Run Command and then terminate
/K Run Command and then return to the CMD prompt.
This is useful for testing, to examine variables

Process to export svn files hangs with Process.Start()

I try to execute a .cmd to export files from SVN, it works manually and in my local machine(WS2003 SP2 IIS Identiy: Local System), but it fails in the execution server (same configuration).
The script I execute is:
echo.%Date%-%Time%- Username %username%>>c:\vpcheckcode\logsvn.txt
svn export %svnUrl% %srcFolder% --force --username %usr% --password %psw%
If I try simply to copy a file, no svn, it works.
When I execute it manually it logs my user and it exports the files.
On develop PC it doesn't log the user but it works, in execution server it doesn't log the user and it doesn't works.
I try to execute the .cmd in this way:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.FileName = strFileName;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = svnUrl + " " + srcFolder+ " " + usr+" "+psw;
using (Process exeProcess = Process.Start(startInfo))
{
pid = exeProcess.Id;
EventLog.WriteEntry("VPCheckCodeSrvDll.ExecuteScriptSVN", "avviato pid svn: " + pid.ToString(), EventLogEntryType.Warning);
if (!exeProcess.WaitForExit((int)_svnExportTimeout))
{
exeProcess.Kill();
The process hangs untill it has been killed.
C:\Documents and Settings\myuser>tlist 4980
4980 cmd.exe
CWD: c:\windows\system32\inetsrv\
CmdLine: cmd /c ""C:\ANALISI\000000-xx-v90\SVN\svnExport.cmd" https://svn.mysite.local/repos/HA/branches/H
VirtualSize: 11332 KB PeakVirtualSize: 15492 KB
WorkingSetSize: 1832 KB PeakWorkingSetSize: 1848 KB
NumberOfThreads: 1
2704 Win32StartAddr:0x4ad07670 LastErr:0x000000cb State:Waiting
5.2.3790.3959 shp 0x4AD00000 cmd.exe
5.2.3790.4937 shp 0x7C800000 ntdll.dll
5.2.3790.5069 shp 0x77E40000 kernel32.dll
7.0.3790.3959 shp 0x77BA0000 msvcrt.dll
5.2.3790.4455 shp 0x7D1E0000 ADVAPI32.dll
5.2.3790.4759 shp 0x77C50000 RPCRT4.dll
5.2.3790.4455 shp 0x76F50000 Secur32.dll
5.2.3790.4033 shp 0x77380000 USER32.dll
5.2.3790.4396 shp 0x77C00000 GDI32.dll
5.2.3790.3959 shp 0x71BD0000 MPR.dll
5.2.3790.3959 shp 0x76290000 IMM32.DLL
Any suggestion?
I did something similar. Try the following:
Change : startInfo.Arguments = svnUrl + " " + srcFolder+ " " + usr+" "+psw;
to : startInfo.Arguments = String.Format("{0} \"{1}\" --username {2} --password {3}", svnUrl, srcFolder, usr, psw);
I am making the assumption that your usr and psw variables do not contain the parameter information for subversion. Also, my destination included the file name (I can't see your full command line as it is cut off) and also contained spaces, so I had to enclose it within quotes. Your svnUrl should have "%20" in place of spaces if you have any (again, the full URL is not visible).

To run cmd as administrator along with command?

Here is my code:
try
{
ProcessStartInfo procStartInfo = new ProcessStartInfo(
"cmd.exe",
"/c " + command);
procStartInfo.UseShellExecute = true;
procStartInfo.CreateNoWindow = true;
procStartInfo.Verb = "runas";
procStartInfo.Arguments = "/env /user:" + "Administrator" + " cmd" + command;
///command contains the command to be executed in cmd
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I want to keep
procStartInfo.UseShellExecute = true
procStartInfo.RedirectStandardInput = false;
Is it possible to execute the command without using process.standardinput?
I try to execute command I've passed in argument but the command does not executes.
As #mtijn said you've got a lot going on that you're also overriding later. You also need to make sure that you're escaping things correctly.
Let's say that you want to run the following command elevated:
dir c:\
First, if you just ran this command through Process.Start() a window would pop open and close right away because there's nothing to keep the window open. It processes the command and exits. To keep the window open we can wrap the command in separate command window and use the /K switch to keep it running:
cmd /K "dir c:\"
To run that command elevated we can use runas.exe just as you were except that we need to escape things a little more. Per the help docs (runas /?) any quotes in the command that we pass to runas need to be escaped with a backslash. Unfortunately doing that with the above command gives us a double backslash that confused the cmd parser so that needs to be escaped, too. So the above command will end up being:
cmd /K \"dir c:\\\"
Finally, using the syntax that you provided we can wrap everything up into a runas command and enclose our above command in a further set of quotes:
runas /env /user:Administrator "cmd /K \"dir c:\\\""
Run the above command from a command prompt to make sure that its working as expected.
Given all that the final code becomes easier to assemble:
//Assuming that we want to run the following command:
//dir c:\
//The command that we want to run
string subCommand = #"dir";
//The arguments to the command that we want to run
string subCommandArgs = #"c:\";
//I am wrapping everything in a CMD /K command so that I can see the output and so that it stays up after executing
//Note: arguments in the sub command need to have their backslashes escaped which is taken care of below
string subCommandFinal = #"cmd /K \""" + subCommand.Replace(#"\", #"\\") + " " + subCommandArgs.Replace(#"\", #"\\") + #"\""";
//Run the runas command directly
ProcessStartInfo procStartInfo = new ProcessStartInfo("runas.exe");
procStartInfo.UseShellExecute = true;
procStartInfo.CreateNoWindow = true;
//Create our arguments
string finalArgs = #"/env /user:Administrator """ + subCommandFinal + #"""";
procStartInfo.Arguments = finalArgs;
//command contains the command to be executed in cmd
using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
{
proc.StartInfo = procStartInfo;
proc.Start();
}
why are you initializing the process object with arguments and then later on override those Arguments? and btw: the last bit where you set Arguments you concatenate 'command' right upto 'cmd', that doesn't make much sense and might be where it fails (looks like you're missing a space).
Also, you are currently using the standard command line, you might want to look into using the runas tool instead. you can also call runas from command line.
Also, why are you running 'command' from the command line? why not start it directly from Process.Start with admin privileges supplied then and there? here's a bit of pseudocode:
Process p = Process.Start(new ProcessStartInfo()
{
FileName = <your executable>,
Arguments = <any arguments>,
UserName = "Administrator",
Password = <password>,
UseShellExecute = false,
WorkingDirectory = <directory of your executable>
});

Running cmd commands via .NET?

System.Diagnostics.Process proc0 = new System.Diagnostics.Process();
proc0.StartInfo.FileName = "cmd";
proc0.StartInfo.WorkingDirectory = Path.Combine(curpath, "snd");
proc0.StartInfo.Arguments = omgwut;
And now for some background...
string curpath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
omgwut is something like this:
copy /b a.wav + b.wav + ... + y.wav + z.wav output.wav
And nothing happens at all. So obviously something's wrong. I also tried "copy" as the executable, but that doesn't work.
Try the prefixing your arguments to cmd with /C, effectively saying cmd /C copy /b t.wav ...
According to cmd.exe /? using
/C <command>
Carries out the command specified by
string and then terminates
For your code, it might look something like
// ..
proc0.StartInfo.Arguments = "/C " + omgwut;
Notes:
A good way to test whether your command is going to work is to actually try it from a command prompt. If you try to do cmd.exe copy ... you'll see that the copy doesn't occur.
There are limits to the length of the arguments you can pass as arguments. From MSDN: "The maximum string length is 2,003 characters in .NET Framework applications and 488 characters in .NET Compact Framework applications."
You can bypass the shelling out to command by using the System.IO classes to open the files and manually concatenate them.
Try this it might help you.. Its working with my code.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
}
catch (Exception objException)
{
// Log the exception
}
Even you can try this.. this is even better.
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="iexplore";
proc.StartInfo.Arguments="http://www.microsoft.com";
proc.Start();
proc.WaitForExit();
MessageBox.Show("You have just visited " + proc.StartInfo.Arguments);
Daniels cmd /c idea will work. Keep in mind there is a limit to the length of a command line probably 8k in your case see this for details.
Since you are in a .Net app anyway, File.Copy may be quite a bit easier/cleaner than this approach.

Categories