2016-11-03 41 views
3

我有多個非常大的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

你運行的進程是否等待用戶輸入? –

回答

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

嘗試/ C以下行替換/ K

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