Search code examples
c#sql-serverwindows-servicesbcp

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


I want to get data from all tables of specific database. I have generated few BCP statements in sql. Now i need to execute these bcp statements from windows service using batch file in c#.

I have following bcp statements:

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

Help appreciated.


Solution

  • Finally here is working code:

    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);
                }
    }