简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM