Rashmi Pandit
Rashmi Pandit

Reputation: 23868

Need to run BCP utility through .net code

How can I run the Bulk Copy Program (BCP) utility of SQL Server through .Net code?

Upvotes: 3

Views: 3653

Answers (4)

Nazeer Sayyed
Nazeer Sayyed

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

NinethSense
NinethSense

Reputation: 9028

Here are some possible options:

  1. From .NET 2.0, we can use SqlBulkCopy class
  2. Use BULK INSERT Query
  3. Use an integration service package (SISS).

...and

  1. If you still need bcp utility, then you can run it as a process... which I will reccomend less.

Upvotes: 1

Binary Worrier
Binary Worrier

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

Andomar
Andomar

Reputation: 238296

Take a look at the SqlBulkCopy class. And there's another article with examples.

Upvotes: 3

Related Questions