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=开发者_StackOverflowtrue;
pInfo.StartInfo.FileName =bat file name ;
pInfo.StartInfo.RedirectStandardOutput = true;
pInfo.Start();
Could anyone help me?
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.
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.
Should it not be pInfo.UseShellExecute = true;
for a batch file?
This is a rights issue, service need rights to run batch file you can fix rights issues as follow
- Install you service
- In windows services find your newly created service
- Right click on service, click on properties
- Under ‘logOn’ tab select radio button ‘Local system account’ and also select ‘allow service to interact with desktop’
精彩评论