C# cmd bcp 导出数据

背景需求:应用系统间数据自动同步处理,要求高效无人工干预

技术实现:C#启动cmd,通过BCP命令传入必要参数,实现数据导出

/// <summary>

/// cmd下,启动应用程序命令

/// 不显示命令窗口

/// </summary>

/// <param name="programExePath">指定应用程序的完整路径</param>

/// <param name="programParmStr">执行命令行参数</param>

public bool StartCmd(string programExePath, string programParmStr)

{

bool result = false;

Process myPro = new Process();

try

{

using (myPro)

{

//如果调用程序路径中有空格时,cmd命令执行失败,可以用双引号括起来 ,在这里两个引号表示一个引号(转义)

string str = "";

if (programExePath.Trim() == "")

str = string.Format(@"{0} {1}", programParmStr, "&exit");

else

str = string.Format(@"""{0}"" {1} {2}", programExePath, programParmStr, "&exit");

ProcessStartInfo StartInfo = new ProcessStartInfo();

//设定需要执行的命令

StartInfo.FileName = "cmd.exe";

//StartInfo.Arguments = str;

//不使用系统外壳程序启动

StartInfo.UseShellExecute = false;

//重定向输入

StartInfo.RedirectStandardInput = true;

//重定向输出

StartInfo.RedirectStandardOutput = true;

StartInfo.RedirectStandardError = true;

//不创建窗口

StartInfo.CreateNoWindow = true;

myPro.StartInfo = StartInfo;

myPro.Start();

myPro.StandardInput.WriteLine(str);

//myPro.StandardOutput.ReadToEnd();

myPro.StandardInput.AutoFlush = true;

myPro.StandardOutput.ReadToEnd();

myPro.WaitForExit();

result = true;

}

}

catch(Exception er)

{

myPro.Close();

throw new Exception("错误006:"+er.Message);

}

return result;

}