您还可以从 C# 调用 SqlPackage.exe 并将其包装在 ProcessStartInfo 中(即从 C# 中执行 shell 命令。我从堆栈溢出的其他地方获取此代码并修改它以在发生错误时执行 Console.ReadLine()我们处于调试模式;想象您传入的命令是 SqlPackage.exe;然后您可以将错误消息更改为红色并暂停控制台窗口:
public void ExecuteCommandSync(object command, string message)
{
Console.WriteLine(message);
Console.WriteLine("------------------------------------------------------------------- ");
Console.WriteLine(" ");
Console.WriteLine("Executing command: " + command);
Console.WriteLine(" ");
Console.WriteLine("------------------------------------------------------------------- ");
Console.WriteLine(" ");
// create the ProcessStartInfo using "cmd" as the program to be run,
// and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows,
// and then exit.
var procStartInfo = new ProcessStartInfo("cmd", "/c " + command)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
// Do not create the black window.
// Now we create a process, assign its ProcessStartInfo and start it
var proc = new Process { StartInfo = procStartInfo };
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
// Get the output into a string
var result = proc.StandardOutput.ReadToEnd();
string err = proc.StandardError.ReadToEnd();
// write the error and pause (if DEBUG)
if (err != string.Empty)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(err);
Console.ResetColor();
#if DEBUG
Console.WriteLine("Press enter to continue...");
Console.ReadLine();
#endif
}
proc.WaitForExit();
// Display the command output.
Console.WriteLine(result);
Console.WriteLine(" ");
Console.WriteLine("------------------------------------------------------------------- ");
Console.WriteLine(" ");
Console.WriteLine("Finished executing command: " + command);
Console.WriteLine(" ");
Console.WriteLine("------------------------------------------------------------------- ");
Console.WriteLine(" ");
}