sabato 20 aprile 2013

Executing Batch File in C#

http://stackoverflow.com/questions/5519328/executing-batch-file-in-c-sharp


I'm trying to execute a batch file in C# but i'm not getting any luck doing it.
I've found multiple examples on the internet doing it but it is not working for me.
        public 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();

        MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
    }
The command string contains the name of the batch file (stored in system32) and some files it should manipulate. (Example: txtmanipulator file1.txt file2.txt file3.txt) When I execute the batch file manually it works correctly.
When executing the code it gives me an ExitCode: 1 (Catchall for genral errors)
What am I doing wrong? Thanks in advance!
share|edit|flag
2
You don't show what command is. If it contains paths with spaces, you 'll need to put quotes around them.– Jon Apr 1 '11 at 22:01
@Jon I've done that, that isn't the problem. Thanks for your input! – Wesz-T Apr 1 '11 at 22:05
Is something in your batch file failing? You might want to set the WorkingDirectory (or whatever that property is called) for your process. – Jonas Apr 1 '11 at 22:10
Well, when I execute the code in command manually (Start --> Run) it runs correctly. I've added the WorkingDirectory now and set it to system32, but i still get the ErrorCode:1 – Wesz-T Apr 1 '11 at 22:17
add comment

4 Answers


up vote15down voteaccepted
This should work. You could try to dump out the contents of the output and error streams in order to find out what's happening:
static void ExecuteCommand(string command)
{
    int exitCode;
    ProcessStartInfo processInfo;
    Process process;

    processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = false;
    // *** 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();

    exitCode = process.ExitCode;

    Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
    Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
    Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
    process.Close();
}

static void Main()
{
    ExecuteCommand("echo testing");
}   
* EDIT *
Given the extra information in your comment below I was able to recreate the problem. There seems to be some security setting that results in this behaviour (haven't investigated that in detail).
This does work if the bat file is not located in c:\windows\system32. Try moving it to some other location, e.g. the location of your executable. Note that keeping custom bat files or executables in the Windows directory is bad practice anyway.
share|edit|flag
Thanks! now i actually can see what the error is. "C:\Windows\System32\txtmanipulator.bat is not recognized as an internal or external command, program or batchfile" (Translated from dutch) Which is odd. Because when i run txtmanipulator from the commandline it executes perfectly. – Wesz-T Apr 1 '11 at 22:42
2
I was able to recreate your problem, check out the addition to the answer. – steinar Apr 1 '11 at 23:46
Thanks man! It works! I had to change some things but it works. I'll post de solution. – Wesz-T Apr 2 '11 at 0:31
This approach is not applicable when I run "pg_dump ... > dumpfile" which dumps a 27 GB database to dumpfile – Paul Oct 29 '12 at 17:28
add comment

System.Diagnostics.Process.Start("c:\\batchfilename.bat");
this simple line will execute the batch file.
share|edit|flag
The simplest way. I also use this. – alexandrudicu Oct 9 '12 at 12:55
add comment

After some great help from steinar this is what worked for me:
After some great help from steinar this is what worked for me:

        public void ExecuteCommand(string command)
    {
        int ExitCode;
        ProcessStartInfo ProcessInfo;
        Process process;

        ProcessInfo = new ProcessStartInfo(Application.StartupPath + "\\txtmanipulator\\txtmanipulator.bat", command);
        ProcessInfo.CreateNoWindow = true;
        ProcessInfo.UseShellExecute = false;
        ProcessInfo.WorkingDirectory = Application.StartupPath + "\\txtmanipulator";
        // *** 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();

        ExitCode = process.ExitCode;

        MessageBox.Show("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
        MessageBox.Show("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
        MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
        process.Close();
    }
Thanks Steinar!
share|edit|flag
add comment

It works fine. I tested it like this:
        String command = @"C:\Doit.bat";

        ProcessInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
        // ProcessInfo.CreateNoWindow = true;
I commented out turning off the window so I could SEE it run.
share|edit|flag

Nessun commento: