-1

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.

SHEKHAR SHETE
  • 5,964
  • 15
  • 85
  • 143
  • Why not use GetSchema? https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection.getschema?force_isolation=true&view=dotnet-plat-ext-5.0 – jdweng May 25 '21 at 13:21
  • Why a batch file, why not [`Process.Start`](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.start?view=net-5.0) directly from C# – Charlieface May 25 '21 at 13:31
  • will u please give a sample code to execute bcp commands from C#? – SHEKHAR SHETE May 25 '21 at 13:42

1 Answers1

0

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);
            }
}
SHEKHAR SHETE
  • 5,964
  • 15
  • 85
  • 143