我想从C#控制台应用程序运行BCP,并能够检测BCP返回CMD的语法,权限或其他错误。我尝试过ErrorDataReceived事件,但在我看来它在任何情况下都不会触发。能否帮我解决这个问题,谢谢
processCMD("bcp", String.Format("\"select 'COUNTRY', 'MONTH' union all SELECT COUNTRY, cast(MONTH as varchar(2)) FROM DBName.dbo.TableName\" queryout {0}FILE_NAME.csv -c -t; -T -{1}", ExportDirectory, SQLServer));
static void processCMD(string fileName, string arguments)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = fileName;
proc.StartInfo.Arguments = arguments;
proc.ErrorDataReceived += new DataReceivedEventHandler(NetErrorDataHandler);
proc.Start();
proc.WaitForExit();
}
private static void NetErrorDataHandler(object sendingProcess, DataReceivedEventArgs errLine)
{
Console.WriteLine(errLine);
Console.ReadLine();
// throw Exception ...
}
/ - 最终解决方案:----------------------------------------- ------------- /
static void processCMD(string fileName, string arguments)
{
StringBuilder cmdOutput = new StringBuilder();
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = fileName;
proc.StartInfo.Arguments = arguments;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
cmdOutput.Append(proc.StandardOutput.ReadLine());
}
proc.WaitForExit();
if(!cmdOutput.ToString().Contains("successfully bulk-copied"))
throw new BCPError(cmdOutput.ToString());
}
public class BCPError : Exception
{
public BCPError()
{
}
public BCPError(string message)
: base(message)
{
}
public BCPError(string message, Exception inner)
: base(message, inner)
{
}
}
如果它被抛出,您可以显示错误,例如e.ToString();
答案 0 :(得分:1)
由于BCP是一个命令行程序,您应该期望stdout
成为控制台,除非您重定向它。你可以这样试试:
static string processCMD(string fileName, string arguments)
{
StringBuilder output = new StringBuilder();
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = fileName;
proc.StartInfo.Arguments = arguments;
proc.UseShellExecute = false;
proc.RedirectStandardOutput = true;
proc.CreateNoWindow = true;
proc.Start();
while (!proc.StandardOutput.EndOfStream) {
output.Append(proc.StandardOutput.ReadLine());
}
proc.WaitForExit();
return output.ToString();
}