C# CMD with command not executed [duplicate] - c#

In C# WPF: I want to execute a CMD command, how exactly can I execute a cmd command programmatically?

Here's a simple example :
Process.Start("cmd","/C copy c:\\file.txt lpt1");

As mentioned by the other answers you can use:
Process.Start("notepad somefile.txt");
However, there is another way.
You can instance a Process object and call the Start instance method:
Process process = new Process();
process.StartInfo.FileName = "notepad.exe";
process.StartInfo.WorkingDirectory = "c:\temp";
process.StartInfo.Arguments = "somefile.txt";
process.Start();
Doing it this way allows you to configure more options before starting the process. The Process object also allows you to retrieve information about the process whilst it is executing and it will give you a notification (via the Exited event) when the process has finished.
Addition: Don't forget to set 'process.EnableRaisingEvents' to 'true' if you want to hook the 'Exited' event.

if you want to start application with cmd use this code:
string YourApplicationPath = "C:\\Program Files\\App\\MyApp.exe"
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.FileName = "cmd.exe";
processInfo.WorkingDirectory = Path.GetDirectoryName(YourApplicationPath);
processInfo.Arguments = "/c START " + Path.GetFileName(YourApplicationPath);
Process.Start(processInfo);

Using Process.Start:
using System.Diagnostics;
class Program
{
static void Main()
{
Process.Start("example.txt");
}
}

How about you creat a batch file with the command you want, and call it with Process.Start
dir.bat content:
dir
then call:
Process.Start("dir.bat");
Will call the bat file and execute the dir

You can use this to work cmd in C#:
ProcessStartInfo proStart = new ProcessStartInfo();
Process pro = new Process();
proStart.FileName = "cmd.exe";
proStart.WorkingDirectory = #"D:\...";
string arg = "/c your_argument";
proStart.Arguments = arg;
proStart.WindowStyle = ProcessWindowStyle.Hidden;
pro.StartInfo = pro;
pro.Start();
Don't forget to write /c before your argument !!

Argh :D not the fastest
Process.Start("notepad C:\test.txt");

Are you asking how to bring up a command windows? If so, you can use the Process object ...
Process.Start("cmd");

You can do like below:
var command = "Put your command here";
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.WorkingDirectory = #"C:\Program Files\IIS\Microsoft Web Deploy V3";
procStartInfo.CreateNoWindow = true; //whether you want to display the command window
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
label1.Text = result.ToString();

In addition to the answers above, you could use a small extension method:
public static class Extensions
{
public static void Run(this string fileName,
string workingDir=null, params string[] arguments)
{
using (var p = new Process())
{
var args = p.StartInfo;
args.FileName = fileName;
if (workingDir!=null) args.WorkingDirectory = workingDir;
if (arguments != null && arguments.Any())
args.Arguments = string.Join(" ", arguments).Trim();
else if (fileName.ToLowerInvariant() == "explorer")
args.Arguments = args.WorkingDirectory;
p.Start();
}
}
}
and use it like so:
// open explorer window with given path
"Explorer".Run(path);
// open a shell (remanins open)
"cmd".Run(path, "/K");

Related

How to take window ID of a created process in c#?

I am working on a C# .net core project.I created a process to run "xdotool windowactivate $windowpid".I should store the windowID which process run on it.The solution could be any property of xdotool which i couldn't find,or Is there any way to take windowId of a process when it is created?
Another Try is that:
I created my pages with this method. I tried to take mainwindowtitle of process;because of single process,i couldn't take the titles.
static List<string> chromeTitles = new List<string>();
public static Process StartChrome(string filePath)
{
string dataDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Chrome-UserData");
filePath += " --user-data-dir=" + dataDirectory;
var Chrome = new Process
{
StartInfo =
{
FileName = "C:/Program/chrome.exe",
Arguments = filePath,
UseShellExecute = false,
CreateNoWindow=true,
WindowStyle = ProcessWindowStyle.Maximized,
}
};
Chrome.Start();
string title = Chrome.MainWindowTitle;
chromeTitles.Add(title);
}
Then I call it :
StartChrome("https://tr.wikipedia.org/wiki/Anasayfa");
Thread.Sleep(2000);
StartChrome("https://tureng.com/");
You can use the Process class for accessing more capabilities.
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "xdotool.exe";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.Arguments = $"windowactivate $windowpid";
process.StartInfo = startInfo;
process.Start();
To get the PID of the process that got run by the code, you can use Process.ID property:
process.Id;
if you want to read the output, you can add this code:
string output = process.StandardOutput.ReadToEnd();
To get Output, startInfo.RedirectStandardOutput should be True.

How do I execute a shell script in C#?

I have one file which contains a Unix shell script. So now I wanted to
run the same in .NET. But I am unable to execute the same.
So my point is, is it possible to run the Unix program in .NET? Is there any API like NSTask in Objective-C for running Unix shell scripts so any similar API in .NET?
It has been answered before. Just check this out.
By the way, you can use:
Process proc = new Process {
StartInfo = new ProcessStartInfo {
FileName = "program.exe",
Arguments = "command line arguments to your executable",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
After that start the process and read from it:
proc.Start();
while (!proc.StandardOutput.EndOfStream) {
string line = proc.StandardOutput.ReadLine();
// Do something with line
}
ProcessStartInfo frCreationInf = new ProcessStartInfo();
frCreationInf.FileName = #"C:\Program Files\Git\git-bash.exe";
frCreationInf.Arguments = "Test.sh";
frCreationInf.UseShellExecute = false;
var process = new Process();
process.StartInfo = frCreationInf;
process.Start();
process.WaitForExit();

c# run command not executing the command

I want to run this:
string command = "echo test > test.txt";
System.Diagnostics.Process.Start("cmd.exe", command);
It's not working, what am I doing wrong?
You are missing to pass the /C switch to cmd.exe to indicate that you want to execute a command. Also notice that the command is put in double quotes:
string command = "/C \"echo test > test.txt\"";
System.Diagnostics.Process.Start("cmd.exe", command).WaitForExit();
And if you don't want to see the shell window you could use the following:
string command = "/C \"echo test > test.txt\"";
var psi = new ProcessStartInfo("cmd.exe")
{
Arguments = command,
UseShellExecute = false,
CreateNoWindow = true
};
using (var process = Process.Start(psi))
{
process.WaitForExit();
}
This should sort of get you started:
//create your command
string cmd = string.Format(#"/c echo Hello World > mydata.txt");
//prepare how you want to execute cmd.exe
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
psi.Arguments = cmd;//<<pass in your command
//this will make echo's and any outputs accessiblen on the output stream
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process p = Process.Start(psi);
//read the output our command generated
string result = p.StandardOutput.ReadToEnd();

How to run CL.exe using Process.Start()?

I have following code
using (StreamWriter outfile = new StreamWriter(#"f:\trial.cpp"))
{
outfile.Write(txtCode.InnerText);
}
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo(#"cl.exe", #" 'trial.cpp'");
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.UserName = "asdasd";
SecureString secureString = new SecureString();
foreach (char c in "abcded")
{
secureString.AppendChar(c);
}
procStartInfo.Password = secureString;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
procStartInfo.WorkingDirectory = #"f:\";
// 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();
How to pass file name as parameter? Above code doesn't run and I have tried all full path, different path options.
can anyone help?
The argument is set incorrectly. You have:
var procStartInfo = new ProcessStartInfo(#"cl.exe", #" 'trial.cpp'");
Where there are spaces and single quotes in the name. Try:
var procStartInfo = new ProcessStartInfo(#"cl.exe", #"trial.cpp");
EDIT:
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "CL.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "trial.cpp";
try
{
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch
{
// error handling
}
The point here is that CL is a command line executable, not a windows GUI application.
http://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx
http://msdn.microsoft.com/en-us/library/kezkeayy.aspx
http://msdn.microsoft.com/en-us/library/9s7c9wdw.aspx
If the cl.exe is not in the system PATH (which by default it is not) then the start process will not find the executable and it will fail to run.
So I suspect you are seeing the fact that the cl.exe is not in the system PATH.

Execute command line using C#

All I am trying to do is send a command that opens a model with the program.exe
Supposed to be super simple!
Ex:
"C:\Program Files (x86)\River Logic\Enterprise Optimizer 7.4 Developer\EO74.exe" "C:\PauloXLS\Constraint Sets_1.cor"
The line above works well if pasted on the command prompt window.
However, when trying to pass the same exact string on my code it gets stuck on C:\Program
string EXE = "\"" + #tbx_base_exe.Text.Trim() + "\"";
string Model = "\"" + #mdl_path.Trim()+ "\"";
string ExeModel = EXE + " " + Model;
MessageBox.Show(ExeModel);
ExecuteCommand(ExeModel);
ExeModel is showing te following line on Visual Studio:
"\"C:\\Program Files (x86)\\River Logic\\Enterprise Optimizer 7.4 Developer\\EO74.exe\" \"C:\\PauloXLS\\Constraint Sets_1.cor\""
To me looks like it is the string I need to send in to the following method:
public int ExecuteCommand(string Command)
{
int ExitCode;
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = true;
Process = Process.Start(ProcessInfo);
Process.WaitForExit();
ExitCode = Process.ExitCode;
Process.Close();
return ExitCode;
}
Things I've tried:
Pass only one command at a time (works as expected), but not an option since the model file will open with another version of the software.
Tried to Trim
Tried with # with \"
Can anyone see any obvious mistake? Thanks.
It's pretty straightforward. You just create a command line object then write to it, then to execute it you read back from it using SR.ReadToEnd():
private string GETCMD()
{
string tempGETCMD = null;
Process CMDprocess = new Process();
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo();
StartInfo.FileName = "cmd"; //starts cmd window
StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
StartInfo.CreateNoWindow = true;
StartInfo.RedirectStandardInput = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.UseShellExecute = false; //required to redirect
CMDprocess.StartInfo = StartInfo;
CMDprocess.Start();
System.IO.StreamReader SR = CMDprocess.StandardOutput;
System.IO.StreamWriter SW = CMDprocess.StandardInput;
SW.WriteLine("#echo on");
SW.WriteLine("cd\\"); //the command you wish to run.....
SW.WriteLine("cd C:\\Program Files");
//insert your other commands here
SW.WriteLine("exit"); //exits command prompt window
tempGETCMD = SR.ReadToEnd(); //returns results of the command window
SW.Close();
SR.Close();
return tempGETCMD;
}
Why are you opening a command prompt (cmd.exe)? Just pass the name of the executable.

Categories

Resources