Reputation: 1
I create a C# Windows service project, then I want to run a .bat file, but I find that it does not run
Process pInfo = new Process();
pInfo.StartInfo.UseShellExecute=false;
pInfo.StartInfo.CreateNoWindow=true;
pInfo.StartInfo.FileName =bat file name ;
pInfo.StartInfo.RedirectStandardOutput = true;
pInfo.Start();
Could anyone help me?
Upvotes: 0
Views: 5665
Reputation: 245
This is a rights issue, service need rights to run batch file you can fix rights issues as follow
Upvotes: 0
Reputation: 2986
You can execute cmd.exe with "/C batchfile" as argument. I don't remember if full path to cmd.exe is required, but I'm using it in my code:
Process p = new Process();
p.StartInfo = new ProcessStartInfo();
p.StartInfo.CreateNoWindow = true;
// p.StartInfo.WorkingDirectory = // I usually set this to the bat file's directory
p.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");
p.StartInfo.Arguments = string.Format("/C \"{0}\"", batchFilename);
p.StartInfo.ErrorDialog = false;
p.StartInfo.UseShellExecute = false;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
This code is old so things might have been changed in recent versions of Windows/.NET framework, but it works.
Upvotes: 2
Reputation: 175776
Should it not be pInfo.UseShellExecute = true;
for a batch file?
Upvotes: 1
Reputation: 115488
This is what we use to execute files from the command line:
Process proc = new Process();
StringBuilder sb = new StringBuilder();
string[] aTarget = target.Split(PATH_SEPERATOR);
string errorMessage;
string outputMessage;
foreach (string parm in parameters)
{
sb.Append(parm + " ");
}
proc.StartInfo.FileName = target;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.Arguments = sb.ToString();
proc.Start();
proc.WaitForExit
(
(timeout <= 0)
? int.MaxValue : timeout *
NO_MILLISECONDS_IN_A_SECOND * NO_SECONDS_IN_A_MINUTE
);
errorMessage = proc.StandardError.ReadToEnd();
proc.WaitForExit();
outputMessage = proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
One of the things to check is to make sure that the application trying to execute the bat file has permissions to do so. It's an easy thing to overlook.
Upvotes: 1