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

问题描述:

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

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

/C而不是/ K你可以看到它打开命令提示符和typi ng CMD.EXE /? – Steve

+0

你运行的进程是否等待用户输入? –

从命令提示符:

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 

尝试/ C以下行替换/ K

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