Reputation: 7612
I have a batch file which runs perfectly fine if I give this command in the command prompt.
C:\app> C:\app\Process.bat C:\app\files\uploads c:\app\files file2 <- WORKS
So there are just 3 input parameters.
C:\app\files\uploads : the folder location of input files
c:\app\files : the output folder
file2 : output file name
If I run the batch file from C:\app folder I see the output file I want to automate the process from a console app which will be scheduled job But running in visual studio debug mode or clicking the exe file does nothing. I don't get any kind of exception either.
What can be wrong - permission or other thing I am doing wrong?
This is the C# code
static void Main(string[] args)
{
RunBatchFile(@"C:\app\Process.bat", @"C:\app\files\uploads c:\app\files 123456");
}
public static string RunBatchFile(string fullPathToBatch, string args)
{
using (var proc = new Process
{
StartInfo =
{
Arguments = args,
FileName = fullPathToBatch,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = false,
RedirectStandardError = false
}
})
{
try
{
proc.Start();
}
catch (Win32Exception e)
{
if (e.NativeErrorCode == 2)
{
return "File not found exception";
}
else if (e.NativeErrorCode == 5)
{
return "Access Denied Exception";
}
}
}
return "OK";
}
Upvotes: 0
Views: 6864
Reputation: 12847
2 Issues here:
First problem is you need to execute cmd.exe not the batch file.
Second, you are executing it but you need to wait for the process to complete. Your app is the parent process and because you're not waiting the child process doesn't complete.
You need to issue a WaitForExit():
var process = Process.Start(...);
process.WaitForExit();
Here is what you want to do:
static void ExecuteCommand(string command)
{
int exitCode;
ProcessStartInfo processInfo;
Process process;
processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
process = Process.Start(processInfo);
process.WaitForExit();
exitCode = process.ExitCode;
process.Close();
}
To run your batch file do this from the main():
ExecuteCommand("C:\app\Process.bat C:\app\files\uploads c:\app\files file2");
Upvotes: 1