使用bcp使用c#将数据导出到文本文件

时间:2019-01-06 13:02:17

标签: c# sql bcp

这是我的.bat文件,它可以在命令提示符下使用,但在我的C#代码中却无法使用: 这是.bat文件代码:

bcp "select * from %4.att.Attendance where Date <= '%5' " queryout  "Attendance.txt"  -c  -b  200000 -S %1 -U %2 -P %3 
bcp "select * from %4.att.PairedAttendnce where Date <= '%5' " queryout "PairedAttendnce.txt"  -c -b 200000 -S %1 -U %2 -P %3 
bcp "select * from %4.att.PersonDateStructure where Date <= '%5' " queryout "PersonDateStructure.txt"  -c -b 200000 -S %1 -U %2 -P %3 
bcp "select * from %4.att.dailyResult where Date <= '%5' " queryout "DailyResult.txt"  -c -b 200000 -S %1 -U %2 -P %3 
bcp "select * from %4.att.WPResult where WPID  <= %7  " queryout "WPResult.txt  "  -c -b 200000 -S %1 -U %2 -P %3 
bcp "select * from %4.att.BaseResultCredit where date <= '%5'" queryout "BaseResultCredit.txt"  -c -b 200000 -S %1 -U %2 -P %3 
bcp "select * from %4.att.Credit where StartDate <= '%5' " queryout "Credit.txt"  -c -b 200000 -S %1 -U %2 -P %3 
bcp "select * from %4.Wfo.nwfDoc where SDate  <= '%5'" queryout "nwfDoc.txt"  -c -b 200000 -S %1 -U %2 -P %3 
bcp "select * from %4.Sec.Eventlog where REPLACE(LEFT(CONVERT(VARCHAR, CreateDateTime, 120), 10), '-', '/') <= '%6' " queryout "Eventlog.txt"  -c -b 200000 -S %1 -U %2 -P %3 
bcp "select * from %4.Cms.DDLLog where  REPLACE(LEFT(CONVERT(VARCHAR,  PostTime, 120), 10), '-', '/')  <= '%6' " queryout "DDLLog.txt"  -c -b 200000 -S %1 -U %2 -P %3 

这是c#代码:

 string MyBatchFile = System.IO.Directory.GetCurrentDirectory() + @"\BatchFiles\Export.bat";

            var process = new System.Diagnostics.Process();

            DateTime dt =  PersianDate.ConvertDate.ToEn (dateOfArchive);

            process.StartInfo.FileName = MyBatchFile;
            // process.StartInfo.Arguments = String.Format("\"{0}\"", serverDBIP, ServerDbUserName, ServerDbPassword, ServerDBName, dateOfArchive, dt.ToShortDateString(), wpid);
            process.StartInfo.Arguments = String.Format("\"{0}\"\"{1}\"\"{2}\"\"{3}\"\"{4}\"\"{5}\"\"{6}\"",
            serverDBIP, ServerDbUserName, ServerDbPassword, ServerDBName, dateOfArchive,dt.ToShortDateString(), wpid);

            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute = false;
            bool b = process.Start();
            Thread.Sleep(20000);
            //string errorMessage = process.StandardError.ReadToEnd();
            process.WaitForExit();

            //string outputMessage = process.StandardOutput.ReadToEnd();
            //process.WaitForExit();    
            process.Close();
            return b;

有人知道代码为什么不起作用吗?

1 个答案:

答案 0 :(得分:0)

您的文件很可能是在process.StartInfo.WorkingDirectory下创建的(目前是默认设置)

您需要设置

process.StartInfo.WorkingDirectory = <your-working-dir>

为了能够将批处理结果保存到给定目录中。