简体   繁体   中英

Trouble executing large batch file from C#

I'm executing a batch file from my C# application using the System.Diagnostics classes, updating my GUI with the output along the way, but as soon as my batch file is in excess of a certain number of lines, the process just hangs. The exact amount of lines seems to vary, but I have been able to reproduce it with a simple batch file that prints "Hello Kitty" 316 times:

@echo off
echo Hello Kitty
echo Hello Kitty

etc.

If I remove the 316th line, the batch file executes fine and the forms application behaves as expected, but any more lines causes the process to suspend indefinitely, not producing even one of the first 300 hello kitties.

Here is my code for executing the batch file:

process = new System.Diagnostics.Process();
process.StartInfo.FileName = batchName;
process.StartInfo.Arguments = " < nul";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.Start();

with these declared elsewhere:

protected Process process;
protected StreamReader output;

My main form does something like this (simplified a little):

string output;

while (!proc.Process.HasExited)
{
    proc.Process.WaitForExit(200);

    if (proc.Process.HasExited)
    {
        output = proc.Output.ReadToEnd();
        rtbStatus.AppendText(output);
    }

    Application.DoEvents();
}

I don't understand why it does this, and no examples that I find on the net make any mention of a size limit on batch files. Please advise.

You need to read the output continuously - you cannot wait to the end.

Output will be buffered, so a small amount (usually about 4KB) can be written before the process hangs.

The alternative is to direct the output to a file then read the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM