Reputation: 23868
How can I run the Bulk Copy Program (BCP) utility of SQL Server through .Net code?
Upvotes: 3
Views: 3653
Reputation: 66
I am very late, but may be helpful for someone else.
I had tested this code.
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExportLargeData
{
class Program
{
static void Main(string[] args)
{
string strCmdText;
strCmdText = "/C bcp databasname..tablename out D:\\NewFolder\\filename.csv -S .\\ -c -C RAW -T";
Important is that the argument begins with /C otherwise it won't work. And after -S you have to pass SQL Server Instance in my case its local so I pass .\
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = strCmdText;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
process.Close();
process.Dispose();
}
}
}
If you want to execute stored procedure then the command will be
string proc = "Exec database..storedprocedurename";
string strCmdText = "/C bcp "+ proc + " queryout D:\\NewFolder\\filename.csv -T -c -S .\\";
Upvotes: 0
Reputation: 9028
Here are some possible options:
...and
Upvotes: 1
Reputation: 51739
You can execute this SQL command in a Command object
BULK INSERT <TableName> from '<FileName>' with (FORMATFILE='<FmtFile>')
Replacing the items in angle brackets with proper item names
Upvotes: 2
Reputation: 238296
Take a look at the SqlBulkCopy class. And there's another article with examples.
Upvotes: 3