I want to run BCP from C# console application and be able to detect syntax, permissions or other errors returned by BCP into CMD. I tried ErrorDataReceived event but it seems to me that it does not fire in any case. Can you please help me with this issue, thank you
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 ...
}
/-- FINAL SOLUTION: ------------------------------------------------------ /
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)
{
}
}
and if it is throwed, you can display error for example like e.ToString();
Since BCP is a command line program, you should expect the stdout
to be the console, unless you redirect it. You could try this way:
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();
}