Process C# does not return anything - c#

I'am working with Process, and it has strange behavior. I need to execute code with Process my WebSections.exe program. Interesting thing, when i pass wrong parameters, it show result that it wrong, when i pass correct parameters it does not show anything, like it would not execute anything at all.
So parameters for my program is WebSections.exe f (.xml file).
But if i call with same parameters as in the code but straight out of command-line, it works.
And also i commented the .ExitCode, bacuse it shows: "System.Exception: Program returned with error code 2 at simplepage.". But with it commented it seems to be working.
Process p;
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "C:\\inetpub\\WebSections\\Program\\WebSections.exe";
psi.Arguments = "f C:\\Users\\HrchM\\Desktop\\Program\\Current_Diagram\\diagramResult.xml";
psi.WorkingDirectory = "C:\\inetpub\\WebSections\\TempFolder";
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
p = Process.Start(psi);
try
{
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit(60000);
/* if (p.ExitCode != 0)// returns 255 when it can’t write to the temp folder (C:\inetpub\WebSections, CZ-CRM\IIS_IUSRS, Modify, replace all child objects)
throw new Exception("Program returned with error code " + p.ExitCode); */
ViewData["Content"] = output.ToString();
}
catch (Exception ex)
{
ViewData["Content"] = ex.ToString();
}
finally
{
p.Close();
p.Dispose();
}

Related

Process is not exiting ffmpeg.exe only for the command which detects the silences from a video

The job of the method ExecuteCommandSync is to detect the silences from a video and return the output as string but when I run this code it never bring the value of proc.HasExited as true. If I forcefully drag the debugger to the line
result =proc.StandardOutput.ReadToEnd()
then it never exit the ffmpeg.exe so as a result control never returns back.
Although the same method is working fine for a different command like creating an audio file from a video. In this case proc.HasExited also returns false but it also generates the audio file successfully.
public static string ExecuteCommandSync(string fileName, int timeoutMilliseconds)
{
string result = String.Empty;
string workingDirectory = Directory.GetCurrentDirectory();
try
{
string command = string.Format("ffmpeg -i {0} -af silencedetect=noise=-20dB:d=0.2 -f null -", "\"" + fileName + "\"");
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.WorkingDirectory = workingDirectory;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit(timeoutMilliseconds);
// Get the output into a string
if (proc.HasExited)
{
if (!proc.StandardOutput.EndOfStream)
{
result = proc.StandardOutput.ReadToEnd();
}
else if (!proc.StandardError.EndOfStream)
{
result = "Error:: " + proc.StandardError.ReadToEnd();
}
}
}
catch (Exception)
{
throw;
}
return result;
}
So please advice.

Running batch file containing NuGet commands from C#

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);

C# call java.exe and get result from cmd wrong

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

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.

How to shell execute a file in C#?

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().

Categories

Resources