problem in cmd.exe while i open it from c#
..
when i open start > run > cmd
and write this command ..
c:>msg \server:"192.168.6.5" * "send hello "
the obove command executed correctly
but
when i run cmd from c#.net this command get this error
private void button3_Click(object sender, EventArgs e)
{
Process.Start("cmd.exe");
}
and then write the same command
c:>msg \server:"192.168.6.5" * "send hello "
output message : msg is not recognized as an internal or external command...
what's the problem ??
plz help
1) If you're on 64 bit, you may have to use "C:\windows\sysnative\msg.exe". Or use System.Environment.GetEnvironmentVariable to get the path and then pass it in to a new ProcessStartInfo object. e.g.
string path = System.Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine);
// add in the extra path parts if required
ProcessStartInfo pinfo = new ProcessStartInfo();
pinfo.WorkingDirectory = "whatever";
pinfo.FileName = "CMD.exe";
pinfo.Arguments = "whatever";
pinfo.EnvironmentVariables["Path"] = path;
Then pass that into Process.Start
2) Also, from the documentation "The user must have send message access permission to send a message.", so it will depend on what privileges you're running the process under.
Related
I have a batch script that launches the mariadb in console mode, so it looks likes this:
run-mariadb.bat
#echo off
cd /D mariadb-10.1.14-win32\bin && mysqld.exe --console
#pause
Using a C# WinForm app, I'd like to launch this batch script and get all output onto a RichTextBox.
This is the code I have so far:
// Configure db server process
Process dbServer = new Process();
dbServer.StartInfo.FileName = "cmd";
dbServer.StartInfo.Arguments = "/c start /wait run-mariadb.bat";
dbServer.StartInfo.CreateNoWindow = true;
dbServer.StartInfo.UseShellExecute = false;
dbServer.StartInfo.RedirectStandardOutput = true;
dbServer.StartInfo.RedirectStandardError = true;
dbServer.OutputDataReceived += new DataReceivedEventHandler(HandleDBServerOutput);
dbServer.ErrorDataReceived += new DataReceivedEventHandler(HandleDBServerOutput);
These are my helper methods:
string FormatOutput(string message)
{
return string.Format("[ {0} ] : {1}",
DateTime.Now.ToShortTimeString(),
message);
}
void HandleDBServerOutput(object sender, DataReceivedEventArgs e)
{
this.BeginInvoke(new MethodInvoker(() =>
{
if (!string.IsNullOrEmpty(e.Data))
dbLogsRTB.AppendText(FormatOutput(e.Data));
}));
}
I start the process like this:
// Start database server
dbServer.Start();
dbServer.BeginOutputReadLine();
dbServer.WaitForExit();
When the above executes, a new command prompt window is created and the mariadb is running in there. Any ideas why dbServer.StartInfo.CreateNoWindow = true; is being ignored?
The help for start starts off with:
Starts a separate window to run a specified program or command.
In other words, by running start as part of your command, you'll launch a new window. You can verify this by running start /wait run-mariadb.bat from a command prompt. It launches a new window to run the command.
Consider changing your command to be simply:
dbServer.StartInfo.Arguments = "/c run-mariadb.bat";
To just run the command without starting a new console process.
Basically i want the user to press a button and then the console will write all the appropriate lines for the user.
Here's the code i've written:
private void button6_Click(object sender, EventArgs e)
{
Process Cmd = new Process();
Cmd.StartInfo.FileName = #"C:\windows\system32\cmd.exe";
Cmd.Start();
StreamWriter sw = new StreamWriter(#"C:\windows\system32\cmd.exe");
{
sw.WriteLine = ("hello");
}
}
I tried StreamWriter but doesn't seem to be co-operating.
What you want can't be done, because you need to redirect StandardInput to send commands to cmd and when you do this, the cmd window will close. You still don't explain what exactly you want to archieve, but i can only think of two options:
Create a batch file with all the commands you want to execute and pass it as an argument to Process.
Redirect StandardInput and StandardOutput. This way you should take care of showing all the cmd messages. This is a bit messy and could lead you to deadlocks.
Edit
So at last, what you want is just run a console application with parameters. This is a sample using makecert:
Process ppp = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = #"C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\makecert.exe";
psi.Arguments = "-n 'CN=TempCA' -r -sv TempCA.pvk TempCA.cer";
ppp.StartInfo = psi;
ppp.Start();
you can do something like this
Process Cmd = new Process();
Cmd.StartInfo.FileName = #"makecert.exe"; // enter the correct path
cmd.StartInfo.Argument = "" // pass your aarguemnt
Cmd.Start();
I currently have a piece of code that opens a cmd prompt using admin rights. What I can't seem to manage is to send a couple of commands to be carried out. I currently have the following code:
var proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = #"C:\Windows\System32";
proc.FileName = #"C:\Windows\System32\cmd.exe";
proc.Verb = "runas";
try
{
Process.Start(proc);
Console.WriteLine("Successfully elevated!");
}
catch (Exception)
{
Console.WriteLine("Failed to elevate.");
}
How would I go about adding a few commands for example what if I wanted to change dir then run an exe file? I am sure it is something very simple I have missed. I have tried giving arguements like so:
proc.Arguments = "cd \\temp";
You can call a .exe from a given filepath using a process.
Like the answer in this: Can you execute another EXE file from within a C# console application?
EDIT:
If you want the directory the program is running from with temp at the end you can do:
string filepath = Directory.GetCurrentDirectory() + #"\temp\programToRun.exe";
Where am I going wrong with this? It's like the arguments are not even getting executed, it just opens the command prompt, and that's it. The "results" (StandardOutput) is exactly what shows up when you just open a new command prompt....says Microsoft Windows [Version 6.1.7600] Copyright...blah then the path where the command prompt is starting from.
Anyway, here's the code that I have:
private static void ExecuteProcess(string processFile, string processArguments)
{
ProcessStartInfo psi = new ProcessStartInfo(processFile, processArguments);
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
//psi.CreateNoWindow = true;
Process p = new Process();
p.StartInfo = psi;
try
{
Cursor.Current = Cursors.WaitCursor;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Cursor.Current = Cursors.Default;
if (p.ExitCode == 0)
MessageBox.Show(output, "Results");
else
throw new Exception(p.StandardError.ReadToEnd());
}
catch (Exception ex)
{
Cursor.Current = Cursors.Default;
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
p.Dispose();
}
}
processFile is equal to "cmd.exe"
processArguments is equal to:
csvde -s {servername} -f {filename} -d OU=MyOU,DC=dmz,DC=lan -r "(objectClass=organizationalUnit)" -n
Any help as to why the "arguments" aren't getting executed would be great!
Edit:
One thing I've found so far, Chris's suggestion about the permissions is true, I needed to set:
psi.Verb = "runas";
But when executing the process it didn't look like there was a username associated with the process, so I added this line as well:
psi.UserName = Environment.UserName;
Now I'm getting "the stub received bad data"...
From the docs:
Cmd
Starts a new instance of the command interpreter, Cmd.exe. Used
without parameters, cmd displays Windows XP version and copyright
information.
Syntax cmd [[{/c|/k}] [/s] [/q] [/d] [{/a|/u}] [/t:fg]
[/e:{on|off}] [/f:{on|off}] [/v:{on|off}] string] Top of page
Parameters
/c : Carries out the command specified by string and then
stops.
So you need to:
Pass the full path to the EXE or
Set the working directory to the directory containing the exe
then
Make processFile == "[]csvde.exe", and remove it from processArguments, or
Prepent "/c \"" and append "\"" to processArguments.
I finally got back to working on this and figured out how to get this to work.
I had to specifically set the Username, Password, and Domain of the Process.ProcessStartInfo in order for the process to execute.
I'm trying to run a shell command with elevated permisions in C#. However the following code returns:
The system cannot find the file specified.
string command = System.IO.Path.Combine(Environment.SystemDirectory, "wdsutil.exe");
string args = ""; //Appropriate arguments
ProcessStartInfo psInfo = new ProcessStartInfo(command);
psInfo.Arguments = args;
psInfo.Verb = "runas";
try
{
Process p = Process.Start(psInfo);
p.WaitForExit();
return "Try Done";
}
catch(Exception e)
{
return e.Message;
}
The error exists without the SystemDriectory prefixed as well.
However, the command does not return the error if I execute the command C:\wdsutil (or any other command in C:).
How do I get Process.Start to run these commands in System32
system32 is on newer systems (esp. 64 Bit windows 7 or 2008) not "real"... it is synthezied from some internal directories and when it is accessed it shows different apps (32 vs. 64) different content...
I test ran the code, changing the executable to one that I located in C:\Windows\System32 directory. It runs ok. (I am running Win 7 64 Bit)
Suggestion: Make sure that the exe is present in the
C:\Windows\System32, or wherever you are trying to run it from. Also, make sure it is unblocked if you'd downloaded it from the internet (Right click the exe > Properties > Unblock).
string command = System.IO.Path.Combine(Environment.SystemDirectory, "wscript.exe");
string args1 = ""; //Appropriate arguments
ProcessStartInfo psInfo = new ProcessStartInfo(command);
psInfo.Arguments = args1;
psInfo.Verb = "runas";
try
{
Process p = Process.Start(psInfo);
p.WaitForExit();
//return "Try Done";
}
catch (Exception e)
{
//return e.Message;
}