如何使用 C# 创建批处理文件并执行 bcp 命令?

How to create batch file and execute bcp command using C#?

我想从特定数据库的所有表中获取数据。 我在 sql 中生成了一些 BCP 语句。现在我需要使用 c# 中的批处理文件从 windows 服务执行这些 bcp 语句。

我有以下 bcp 语句:

bcp [MyDB].[dbo].[tbl_UserLocations] out c:\temp\dbo_tbl_UserLocations.txt -S dbinstance.cvxlgn3jt61m.us-east-1.rds.amazonaws.com -U adminusername -P adminpassword -c
bcp [MyDB].[dbo].[tbl_UserTypes] out c:\temp\dbo_tbl_UserTypes.txt -S dbinstance.cvxlgn3jt61m.us-east-1.rds.amazonaws.com -U adminusername -P adminpassword -c

感谢帮助。

最后是工作代码:

public void ExecuteBatchCommands()
{
            try
            {
                Logger.WriteToFile(serviceName + "=> ExecuteBatchCommands() started : " + DateTime.Now.ToLongTimeString());
                Process proc = null;
                proc = new Process();
                //proc.StartInfo.WorkingDirectory = targetDir;
                proc.StartInfo.FileName = "BCPCommands.bat";
                //proc.StartInfo.Arguments = string.Format("10");  //this is argument
                proc.StartInfo.CreateNoWindow = false;
                proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;  //this is for hiding the cmd window...so execution will happen in back ground.
                proc.Start();
                proc.WaitForExit();
                proc = null;
                Logger.WriteToFile(serviceName + "=> ExecuteBatchCommands() ends : " + DateTime.Now.ToLongTimeString());
            }
            catch (Exception ex)
            {
                Logger.WriteToFile(serviceName + "=> ExecuteBatchCommands() => Exception occured while executing batch process at " + DateTime.Now.ToLongTimeString() + " " + ex.StackTrace + " \n" + ex.Message);
            }
}