Starting a Jar file using System.Diagnostics.Process - c#

I have a jar file which I want to run from within C#.
Here's what I have so far:
clientProcess.StartInfo.FileName = #"java -jar C:\Users\Owner\Desktop\myJarFile.jar";
clientProcess.StartInfo.Arguments = "[Something]";
clientProcess.Start();
clientProcess.WaitForExit();
int exitCode = clientProcess.ExitCode;
Unfortunatly I get "System could not find specified file", which makes sense since its not a file its a command.
I've seen code online which tells you to use:
System.Diagnostics.Process.Start("java -jar myprog.jar");
However I need the return codes AND I need to wait for it to exit.
Thanks.

Finally solved it. The filename has to be java and the arguments has to contain the location of the jar file (and anything arguments you want to pass that)
System.Diagnostics.Process clientProcess = new Process();
clientProcess.StartInfo.FileName = "java";
clientProcess.StartInfo.Arguments = #"-jar "+ jarPath +" " + argumentsFortheJarFile;
clientProcess.Start();
clientProcess.WaitForExit();
int code = clientProcess.ExitCode;

You need to set environment variable Path of java.exe executable or specify the full path of java.exe.
ProcessStartInfo ps = new ProcessStartInfo(#"c:\Program Files\java\jdk1.7.0\bin\java.exe",#"-jar C:\Users\Owner\Desktop\myJarFile.jar");
Process.Start(ps);

Related

calling devcon from inside windows forms not working

Plan
The plan is to disable and subsequently enable a device from inside a windows forms application. To test the first building block of my plan, I open cmd with admin privileges and the following works perfectly:
> devcon hwids =ports
> devcon hwids *VID_10C4*
> devcon disable *VID_10C4*
> devcon enable *VID_10C4*
I can see the device being disabled and enabled again in device manager.
I can also achieve all of this by putting the commands into a batch file and running it from cmd with admin privileges. The above tells me that my plan is essentially good.
Application
However, what I actually want to do is achieve the same thing from inside a windows forms application:
I've set the following in the app manifest:
requestedExecutionLevel level="requireAdministrator" uiAccess="false"
For the sake of baby steps, I have checked this, just to ensure that there are no stupid mistakes in paths and whatnot. And it works just fine. The log file shows me the expected output from the dir command.
// Build String
string strCmdText =
"'/c cd " + prodPath +
" && dir " +
" > logs\\logFileEnablePrt.txt \"'";
// Run command
var p = new System.Diagnostics.Process();
var psi = new ProcessStartInfo("CMD.exe", strCmdText);
psi.Verb = "runas"; // admin rights
p.StartInfo = psi;
p.Start();
p.WaitForExit();
However, this does not work. It always returns an empty log file and does not change the device as expected:
// Build String
string strCmdText =
"'/c cd " + prodPath +
" && devcon hwids =ports " +
" > logs\\logFileEnablePrt.txt \"'";
// Run command
var p = new System.Diagnostics.Process();
var psi = new ProcessStartInfo("CMD.exe", strCmdText);
psi.Verb = "runas"; // admin rights
p.StartInfo = psi;
p.Start();
p.WaitForExit();
Error from cmd window is :
'devcon' is not recognized as an internal or external command,
operable program or batch file.
What's going on?
The above has me stumped. I've proved the commands work. I've proved my C# code works. But when I join the 2 together, it doesn't work...
NB: My C# program is running on my D: drive, if that makes any difference...
Updates Based on Comments
#Compo
Using your code, it does exactly the same as with mine. I see an empty log file & no changes made to the device. I've altered the /c to /k so I can see what going on the cmd terminal and I see this:
I've even tried your code C:\\Windows\\System32\\devcon hwids =usb pointing directly at devcon. Also tried \devcon.exe for completeness. The inexplicable error is :
I can see the flipping devcon.exe file sitting right there in the folder! Is there any reason it would not recognise it?
Also, with the command as you wrote it, the log file name is actually named logFileEnablePrt.txt'. I agree that your command looks right, so don't ask me why this happens!
#Panagiotis Kanavos
using your code, I get the following error:
This is at the line p.Start();. I tried putting in devcon.exe, and even the whole path (I checked the folder was in my PATH, and it is). Can't get past this. I actually stumbled on that answer you shared and arrived at this brick wall already.
Here is the code works for me, I don't have ports devices so I change it to usb.
public static void Main()
{
string prodPath = #"c:\devcon\x64";
// Build String
string strCmdText =
"/c \"cd /d " + prodPath +
" && devcon hwids =usb " +
" > log.txt \"";
// Run command
var p = new Process();
var psi = new ProcessStartInfo("CMD.exe", strCmdText);
psi.Verb = "runas"; // admin rights
p.StartInfo = psi;
p.Start();
p.WaitForExit();
}
Worked through a few steps and think I may have an answer...
Just specifying devcon fails as expected...windows cant find the exe as the folder it is in is not in the %PATH% variable in windows..
IF I specify the full path however it works...
It wasnt clear from your original code but if your copy of devcon is sitting in either System32 or Syswow directories you may be hitting an emulation issue as well...see here....
EDIT1:: A way to prove this would be to do Direcory.GetFiles(directory containing devcon) and see if the results line up with what you expect
As for passing arguments through to devcon I'd try something like this as opposed to trying to concatenate one giant cmd line..
A similar example but with netstat:
EDIT 2::Another example but with devcon:
The target platform here for the build was x64
EDIT3::
With my application build set to x86:
After working through the answers and comments above, I seem to have something that reliably works, which obviously I'd like to share back for scrutiny and future use.
So, my function ended up looking like this:
private int enablePort(string action)
{
while (true)
{
// Command Arg
string devconPath = #"c:\Windows\SysNative";
string strCmdText =
"'/c \"cd /d \"" +
devconPath +
"\" && c:\\Windows\\SysNative\\devcon " + action + " *VID_10C4* " +
"> \"" + prodPath + "\\logs\\logFileEnablePrt.txt\"\"";
// Process
var p = new Process();
var psi = new ProcessStartInfo()
{
Arguments = strCmdText,
Verb = "runas",
FileName = "CMD.exe",
UseShellExecute = true
};
p.StartInfo = psi;
p.Start();
p.WaitForExit();
// Grab log output
string logPath = prodPath + "\\logs\\logFileEnablePrt.txt";
Console.WriteLine("logPath = " + logPath);
string tempFile = System.IO.File.ReadAllText(logPath);
System.Console.WriteLine("Contents of WriteText.txt = \n{0}", tempFile);
// Check if it worked
var success = false;
if (tempFile.Contains(action))
{
success = true;
return 0;
}
// Error -> Allow user to try again!
if (MessageBox.Show("Was unable to " + action + " Test Jig COM port. Unlug & Replug USB. Check COM port is enabled if not working.", "COM Port Problem", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return -1;
}
}
}
And the calling code was:
this.enablePort("disable");
int milliseconds = 3000;
await Task.Delay(milliseconds);
this.enablePort("enable");
As you can see in the code above, I've logged everything to see what was going on... Stepping through with the debugger, I can now see after the disable:
USB\VID_10C4&PID_EA60\0001 : Disabled
1 device(s) disabled.
And then after the enable:
USB\VID_10C4&PID_EA60\0001 : Enabled
1 device(s) are enabled.
The one extra thing I need to stress is that during testing, I thought I could hook a serial peripheral onto the port and determine whether it could disable and enable successfully by checking the connection. THIS DOES NOT WORK. The above code only works when the port is idle. Perhaps someone who understands the underlying software could hazard an explanation of why this is.

Execute batch file duplicate file name exists, or the file cannot be found

Executing by C# a complicated batch file, that setting session variables example
SET TEST = rainbow
getting the famous
A duplicate file name exists, or the file cannot be found.
I used
string args = string.Format("/k \"cd /d {0} && {1}\"", s.Path, s.Filename + " " + userChoice);
RunBatch("cmd.exe", args, s.Path);
.
.
ProcessStartInfo startInfo = new ProcessStartInfo()
{
UseShellExecute = false,
WorkingDirectory = workingDir,
FileName = cmd,
Arguments = cmdArgs
};
Process.Start(startInfo);
when trying it on simple batch file working. With the complex one getting the error mention above.
--
I tried also to write by C#, a new batch file that has on the first line the
setlocal enableextensions disabledelayedexpansion
, then calling the needed one, and execute this batch by C#, the error again is the same...
any tip?

Sending multiple arguments to cmd C#

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

Process.Start - struggling with arguments to TFS command line

I'm trying to execute TFS via Process.Start but am having some difficulty and I can't understand why. Here's my code snippet:
/// <summary>
/// Get the entire history for a project
/// </summary>
public void GetHistory(String project)
{
ProcessStartInfo info = new ProcessStartInfo();
String fileName = Path.GetTempFileName();
info.Arguments = String.Format("history \"{0}\" /recursive /format:Detailed /noprompt > {1}", "c:\\source\\ " + project, fileName);
info.FileName = "\"C:\\Program Files (x86)\\Microsoft Visual Studio 11.0\\Common7\\IDE\\tf.exe\"";
info.RedirectStandardError = true;
info.UseShellExecute = false;
Process process = new Process();
process.StartInfo = info;
process.Start();
process.WaitForExit();
Console.WriteLine(process.StandardError.ReadToEnd());
Console.WriteLine("History written to " + fileName);
Console.ReadKey();
}
This is resulting in a set of arguments like so (I've just removed the full project name):
I then get the following error:
The history command takes exactly one item.
If I piece the string together and execute in a normal command line however then it works:
Can anyone tell me what I'm missing?
You can't redirect output to a file in the Process.Start arguments. File redirection is a function of the shell.
If you want to put the history into a file, you will need to File.Open the file yourself, read the output of the tf history command and write it to the file.
Or you could use a command script or PowerShell script.

'No such file or directory' if process is run programmatically (from C#)

I have an application that dumps a lot of files to a directory. I want to copy these files to a Hadoop cluster using the hadoop command. I use the following code to run the command.
System.Diagnostics.ProcessStartInfo export = new System.Diagnostics.ProcessStartInfo();
export.RedirectStandardOutput = false;
export.RedirectStandardError = false;
export.UseShellExecute = false;
export.WorkingDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
export.FileName = "hadoop";
export.Arguments = "fs -copyFromLocal " + Path.Combine(dumpDirectory, "*.txt") + " " + hadoopPath));
Console.WriteLine("Copying data: hadoop " + export.Arguments);
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(export);
proc.WaitForExit();
if (proc.ExitCode == 0)
{
IEnumerable<string> files = Directory.EnumerateFiles(dumpDirectory);
foreach (string file in files)
File.Delete(file);
}
else
Console.WriteLine("Error copying to Hadoop: " + proc.ExitCode);
The program writes the following message:
Copying data: hadoop fs -copyFromLocal local/directory/*.txt /user/remote/directory/
copyFromLocal: `local/directory/*.txt': No such file or directory
Error copying to Hadoop: 1
Interestingly, when I run the command manually, the files copy without error.
Also, if the program runs the command without using *.txt and instead calls the command for each file individually, the command succeeds.
Can anyone shed some light on this?
I partially resolved the problem by creating a bash script containing the given command. I ran the bash script programmatically and it worked.
However, I still do not know why the original did not work.

Categories

Resources