user3671271 February 2016

Why is my bcp query not working?

I'm beginner in C#, I want use the bcp utility in C# and to do so, I wrote this code:

 string connstr = "Data Source=192.168.50.172;Initial Catalog=CDRDB;User ID=CDRLOGIN;Password=beh1368421"; 

 //string connstr = "Enter your connection string here";
 System.Diagnostics.Process proc = new System.Diagnostics.Process();
 proc.StartInfo.FileName = "bcp";
 proc.StartInfo.Arguments = @"select * from CDRTABLE"" queryout c:\filename.csv -S 192.168.50.172 -U CDRLOGIN -P beh1368421 -f -w";
 proc.Start();

That code runs, but filename.csv is not created on my C:\ drive. What happened? How can I solve this problem?

Answers


Anil Kumar February 2016

For Bcp executing from System.Diagnostics.Process(), one should use the -c and -CRAW options.

Below is sample code.

string execPath = @"..\bcp.exe";
string localFile = @"MetaData.Table";
string localPath = @"..\OutputFolder";

System.Diagnostics.Process P = new System.Diagnostics.Process();
P.StartInfo.UseShellExecute = false;
P.StartInfo.RedirectStandardOutput = true;
P.StartInfo.RedirectStandardError = true;
P.StartInfo.CreateNoWindow = true;
P.StartInfo.FileName = execPath;

P.StartInfo.Arguments = string.Concat("\"", "MetaData.Table", "\" out \"", localPath, "\\", localFile, ".dat\" -c -C RAW -t\"", separator, "\" -S \"", "(local)", "\" -T");

P.Start();
P.WaitForExit();
P.Close();
P.Dispose();

You can also use BCP in C# code using BULK INSERT Transact-SQL statement and using the ExecuteNonQuery method of SqlCommand.

Something like below will work:

sCommandText = "exec xp_cmdShell 'bcp.exe'"+Database + ".." + TableName + " in "  + 
                 FileName + " -c -q -U " + UserId + " -P " + Password +  "-t  ";

SqlConnection conn = new SqlConnection(ConnectionString);
conn.Open(); 

SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = sCommandText;

return cmd.ExecuteNonQuery();

Post Status

Asked in February 2016
Viewed 3,763 times
Voted 9
Answered 1 times

Search




Leave an answer