I want to using C# process to get result from Command Prompt. The command is "java HelloWorld 1" (I have been build it to HelloWorld.class file using "javac HelloWorld.java")
The java code:
public class HelloWorld {
public HelloWorld() {}
public static void main(String[] args) { System.out.println("STARTED");
try {
int param = Integer.parseInt(args[0].toString());
if (param == 1) {
System.out.println("BASE 64!");
} else if (param == 2) {
System.out.println("MD5!");
} else {
System.out.println("INPUT NOT MATCH!");
}
} catch (Exception ee) {
System.out.println("NO INPUT - ERROR");
}
} }
and The C# code:
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "C:\\Program Files\\Java\\jdk1.6.0_25\\bin\\java.exe";
p.StartInfo.Arguments = "HelloWorld 1";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string strOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
But the strOutput is "".
Can you give me the solution?
Thank you!
The most likely thing is that java cannot find your HelloWorld.class file.
In that case, it will write to the standard error something like
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld
Caused by: java.lang.ClassNotFoundException: HelloWorld
and then a stack trace.
And it will not write anything to the standard output
I suggest you do two things:
1) read from standard error as well and see what that says
2) add a classpath argument prior to the class file
p.StartInfo.Arguments = " -cp C:\\code\\myapp HelloWorld 1";
(Obviously substituting in the correct path to the folder that contains HelloWorld.class)
Another alternative is to set your process start info to the location of HelloWorld:
ProcessStartInfo pInfo = new ProcessStartInfo(#"C:\Program Files\Java\jdk1.6.0_25\bin\java.exe");
pInfo.Arguments = = "HelloWorld";
pInfo.WorkingDirectory = #"C:\JavaFiles";
pInfo.UseShellExecute = false;
pInfo.RedirectStandardOutput = true;
Process javaProc = Process.Start(pInfo);
string output = javaProc.StandarOutput.ReadToEnd();
EDIT: I just realized your p was a Process object. WorkingDirectory is a property of ProcessStartInfo
This is assuming that C:\JavaFiles\HelloWorld.class and C:\JavaFiles\HelloWorld.java exists. You should also follow Greg's advice and read StandardError, as it will help you troubleshoot future problems
Related
I have c# program that I want to run but from the cmd using a command line so here is my question I don't know how to create the command and I don't know how to send the parameter in my command to some function there.
You can use the Process class to execute files
var fileName = "some.exe";
var arguments = "";
var info = new System.Diagnostics.ProcessStartInfo(fileName, arguments);
info.UseShellExecute = false;
info.CreateNoWindow = true;
// if you want read output
info.RedirectStandardOutput = true;
var process = new System.Diagnostics.Process { StartInfo = info };
process.Start();
var output = process.StandardOutput.ReadToEnd();
var error = process.StandardError?.ReadToEnd();
You can create a console application and after generating (by building) .exe file, you can call with the arguments in command line.
Sample Example:
class Program
{
static void Main(string[] args)
{
var a = Convert.ToInt32(args[0]);
var b = Convert.ToInt32(args[1]);
Console.WriteLine(a+b);
}
}
OUTPUT
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");
I have a batch file containing the following commands:
cd C:\myfolder
NuGet Update -self
NuGet pack mypackage.nuspec
myfolder contains mypackage.nuspec and NuGet.exe. I try to run this command with C# using the following function:
private static int ExecuteCommand(string path)
{
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo(path);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = false;
ProcessInfo.WorkingDirectory = new System.IO.FileInfo(path).DirectoryName;
ProcessInfo.EnvironmentVariables["EnableNuGetPackageRestore"] = "true";
// *** Redirect the output ***
ProcessInfo.RedirectStandardError = true;
ProcessInfo.RedirectStandardOutput = true;
Process = Process.Start(ProcessInfo);
Process.WaitForExit();
// *** Read the streams ***
string output = Process.StandardOutput.ReadToEnd();
string error = Process.StandardError.ReadToEnd();
int ExitCode = Process.ExitCode;
Process.Close();
return ExitCode;
}
However, my commands are not executed. What is causing this behavior and what is the solution? Those strings will probably be used in the future, I'll update my question then (just to prevent chriticism :)).
This is the final version of the function:
private static ShellCommandReturn ExecuteCommand(string path)
{
ProcessStartInfo processInfo;
Process process;
processInfo = new ProcessStartInfo(path);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.WorkingDirectory = new System.IO.FileInfo(path).DirectoryName;
processInfo.EnvironmentVariables["EnableNuGetPackageRestore"] = "true";
// *** Redirect the output ***
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
process = Process.Start(processInfo);
process.WaitForExit();
// *** Read the streams ***
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
int exitCode = process.ExitCode;
process.Close();
return new ShellCommandReturn { Error = error, ExitCode = exitCode, Output = output };
}
ShellCommandReturn is a simple custom class with a few data members where error, output and exit code of a shell command are stored.
Thanks.
EDIT: After a certain amount of collaboration :)
The problem is that this is executing in the context of a web application, which doesn't have the same environment variables set.
Apparently setting:
startInfo.EnvironmentVariables["EnableNuGetPackageRestore"] = "true"
(using the naming of my final code below) fixes the problem.
Old answer (still worth reading)
Look at this code:
ProcessInfo = new ProcessStartInfo(path);
ProcessInfo.CreateNoWindow = false;
ProcessInfo.UseShellExecute = true;
ProcessInfo.WorkingDirectory = new System.IO.FileInfo(path).DirectoryName;
Process = Process.Start(path);
You're creating a ProcessStartInfo, but then completely ignoring it. You should be passing it into Process.Start. You should also rename your variables. Conventionally local variables start with lower case in C#. Additionally, it's a good idea to initialize variables at the point of first use, where possible. Oh, and import namespaces so you don't fully qualified names such as System.IO.FileInfo in your code. Finally, object initializers are useful for classes like ProcessStartInfo:
var startInfo = new ProcessStartInfo(path) {
CreateNoWindow = false,
UseShellExecute = true,
WorkingDirectory = new FileInfo(path).DirectoryName;
};
var process = Process.Start(startInfo);
I want to give command name and file path in ProcessStartInfo() method in C#.
So I have a command name("F:\AndroidProjects\AndProj3>) and file path("F:\Android\apache-ant-1.8.2-bin\apache-ant-1.8.2\bin\ant debug") just like that but it is not working and process can not be started.
Please give me a solution for starting the process because command name first execute and after that file path will be execute.
How I can pass the both argument in ProcessStartInfo() method?
public static string BuildAndroidProject()
{
string result="";
// string ProjNameNDLocation = ProjectLocation + "\\" + ProjectName + ">";
try
{
System.Diagnostics.ProcessStartInfo androidBuildProj = new System.Diagnostics.ProcessStartInfo("F:\\AndroidProjects\\AndProj3 F:\\Android\\apache-ant-1.8.2-bin\\apache-ant-1.8.2\\bin\\ant debug");//ProjNameNDLocation, Program.ANDROIDDEBUGGCMD);
androidBuildProj.RedirectStandardOutput = true;
androidBuildProj.UseShellExecute = false;
androidBuildProj.CreateNoWindow = true;
System.Diagnostics.Process androidProcess = new System.Diagnostics.Process();
androidProcess.StartInfo = androidBuildProj;
androidProcess.Start();
result = androidProcess.StandardOutput.ReadToEnd();
androidProcess.Close();
}
catch (Exception e)
{
}
return result;
}
Problem is in the ProcessInfoStart Function. How can I run this command?
Based on the question, the closest I can see is:
using (var proc = Process.Start(new ProcessStartInfo
{
WorkingDirectory = #"F:\AndroidProjects\AndProj3",
FileName = #"F:\Android\apache-ant-1.8.2-bin\apache-ant-1.8.2\bin\ant",
Arguments = "debug"
}))
{
// maybe wait and check exit-code
// proc.WaitForExit();
// int i = proc.ExitCode;
}
I tried using the Process class as always but that didn't work. All I am doing is trying to run a Python file like someone double clicked it.
Is it possible?
EDIT:
Sample code:
string pythonScript = #"C:\callme.py";
string workDir = System.IO.Path.GetDirectoryName ( pythonScript );
Process proc = new Process ( );
proc.StartInfo.WorkingDirectory = workDir;
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = pythonScript;
proc.StartInfo.Arguments = "1, 2, 3";
I don't get any error, but the script isn't run. When I run the script manually, I see the result.
Here's my code for executing a python script from C#, with a redirected standard input and output ( I pass info in via the standard input), copied from an example on the web somewhere. Python location is hard coded as you can see, can refactor.
private static string CallPython(string script, string pyArgs, string workingDirectory, string[] standardInput)
{
ProcessStartInfo startInfo;
Process process;
string ret = "";
try
{
startInfo = new ProcessStartInfo(#"c:\python25\python.exe");
startInfo.WorkingDirectory = workingDirectory;
if (pyArgs.Length != 0)
startInfo.Arguments = script + " " + pyArgs;
else
startInfo.Arguments = script;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
process = new Process();
process.StartInfo = startInfo;
process.Start();
// write to standard input
foreach (string si in standardInput)
{
process.StandardInput.WriteLine(si);
}
string s;
while ((s = process.StandardError.ReadLine()) != null)
{
ret += s;
throw new System.Exception(ret);
}
while ((s = process.StandardOutput.ReadLine()) != null)
{
ret += s;
}
return ret;
}
catch (System.Exception ex)
{
string problem = ex.Message;
return problem;
}
}
Process.Start should work. if it doesn't, would you post your code and the error you are getting?
You forgot proc.Start() at the end. The code you have should work if you call Start().