完成c#中的执行后关闭sqlcmd

时间:2016-11-03 21:52:17

标签: c# command-prompt sqlcmd

我有多个非常大的sql文件,我试图使用sqlcmd在我的C#代码中自动运行。我使用ProcessStartInfo来启动命令提示符,然后从那里运行sqlcmd。但是,一旦sqlcmd完成第一个文件的运行,命令窗口就会保持运行,我的应用程序会挂起“等待退出”。如何在执行我的sql文件后执行命令提示符退出?

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
    }
}

2 个答案:

答案 0 :(得分:1)

从命令提示符:

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)
....

所以你指定了这个选项:

/K      Carries out the command specified by string but remains

答案 1 :(得分:1)

在以下行中尝试使用/ C替换/ K

ProcessInfo = new ProcessStartInfo("cmd.exe", "/C " + commandString);