Home Ask Login Register

Developers Planet

Your answer is one click away!

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=;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 -U CDRLOGIN -P beh1368421 -f -w";

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


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


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

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


Leave an answer

Quote of the day: live life