C# 从C运行BCP时检测到错误#
我想从C#控制台应用程序运行BCP,并能够检测BCP返回到CMD的语法、权限或其他错误。我尝试了ErrorDataReceived事件,但在我看来,它在任何情况下都不会触发。你能帮我解决这个问题吗,谢谢C# 从C运行BCP时检测到错误#,c#,error-handling,bcp,C#,Error Handling,Bcp,我想从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\" query
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()
因为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();
}
所以,我将解析流的结尾是否等于标准行为,以及输出是否不同,然后我可以抛出一个错误,很好。。谢谢,我会尽快试一试