Search code examples
c#command-promptsqlcmd

Close sqlcmd after finishing executing in c#


I have multiple very large sql files that I'm trying to run automatically in my C# code using sqlcmd. I use ProcessStartInfo to launch the command prompt and from there run sqlcmd. However, once sqlcmd finishes running the first file, the command window stays up and my application hangs at "Wait for Exit". How do I make it so my command prompt exits after executing my sql file?

for (int i = 1; i <= fileCount; i++)
{
    string readFile = fileToRead + "_" + i + ".sql";
    string writeFile = fileToWrite + "_" + i + ".txt";

    string commandString = "sqlcmd -S myservername -d mydatabasename -i " + readFile + " -o " + writeFile + " -a 32767";

    ProcessStartInfo ProcessInfo;
    ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + commandString);
    ProcessInfo.CreateNoWindow = true;
    ProcessInfo.UseShellExecute = false;
    ProcessInfo.RedirectStandardOutput = true;

    using (Process Process = Process.Start(ProcessInfo))
    {
        Process.WaitForExit(); //hangs here because window stays open, have to manually exit it to continue
    }
}

Solution

  • From the command prompt:

    D:\>help cmd
    Starts a new instance of the Windows command interpreter
    
    CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:
        [[/S] [/C | /K] string]
    
    /C      Carries out the command specified by string and then terminate
    /K      Carries out the command specified by string but remains
    /S      Modifies the treatment of string after /C or /K (see below)
    ....
    

    So you have specified this option:

    /K      Carries out the command specified by string but remains