Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling bcp from c#

I am needing to call a bcp utility from c# code. Here is what I've got:

var text = 
            "\"EXEC <stored procedure name> @Date=\"1/1/2013\"\" " +
            "queryout \"<network path for file drop>\" -c -t\\0 " +
            "-S <server name> -U <user name> -P <password>";
        var proc = new System.Diagnostics.Process();
        proc.StartInfo.FileName = "bcp";
        proc.StartInfo.Arguments = text;
        proc.Start();

This is a small part of a larger application, but as I've had a devil of a time getting this to work, I've pulled it out into it's own console application for testing. This is literally all that's in the main method. I know the stored proc works in the database, because when I call it from PowerShell, it works fine. However, when debugging this code and stepping into the Start method, the debugger sails past. No error, no hesitation. But the flat file that is intended is never created. Can anyone tell me what I'm doing wrong? In case this matters, the SP creates a null delimited file from tables in a DB.

like image 438
will Avatar asked Sep 16 '25 04:09

will


1 Answers

Try this

    processCMD("bcp", String.Format("\"select 'COUNTRY', 'MONTH' union all SELECT COUNTRY, cast(MONTH as varchar(2)) FROM DBName.dbo.TableName\" queryout {0}FILE_NAME.csv -c -t; -T -{1}", ExportDirectory, SQLServer));


    static void processCMD(string fileName, string arguments) 
            {

                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo.FileName = fileName;
                proc.StartInfo.Arguments = arguments;
                proc.Start();
                proc.WaitForExit();

            }
like image 125
Muflix Avatar answered Sep 19 '25 11:09

Muflix