研究了好几个小时才搞定
函数体
public static string ExcuteBatFile(string batPath, ref string errMsg)
{
try
{
if (errMsg == null) throw new ArgumentNullException("errMsg");
string output;
using (Process process = new Process())
{
FileInfo file = new FileInfo(batPath);
if (file.Directory != null)
{
process.StartInfo.WorkingDirectory = file.Directory.FullName;
}
process.StartInfo.FileName = batPath;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
process.WaitForExit();
output = process.StandardOutput.ReadToEnd();
errMsg = process.StandardError.ReadToEnd();
}
return output + "|||||" + errMsg;
}
catch (Exception ex)
{
return ex.Message;
}
}
调用:
private void button2_Click(object sender, EventArgs e)
{
// var bat = System.Threading.Thread.GetDomain().BaseDirectory + "EZHbozmZpC.bat";
string path = @"C:\sql0\" + textBox1.Text;
//string path = @"C:\sql0\EZHbozmZpC.bat";
string errMsg = string.Empty;
string output = ExcuteBatFile(path, ref errMsg);
textBox3.Text = output;
}
返回值:
C:\sql0>F:
F:\>cd F:\soft\oracle\sqluldr2
F:\soft\oracle\sqluldr2> ********
0 rows exported at 2022-04-15 19:21:32, size 0 MB.
734 rows exported at 2022-04-15 19:21:32, size 0 MB.
output file c:\888.csv closed at 734 rows, size 0 MB.
|||||
c#生成bat文件,并且执行
private void button2_Click(object sender, EventArgs e)
{
string batfile = getStr(10);
string fileContent = "F:" + System.Environment.NewLine + "cd F:\\soft\\oracle\\sqluldr2" + System.Environment.NewLine
+ "sqluldr264 USER=***/***@*** QUERY=\"select * from " + textBox1.Text + "\" head=yes FILE=c:\\"+ batfile + ".csv";
string filePath = "c:\\sql0\\" + batfile +".bat";
if (!File.Exists(filePath))
{
FileStream fs1 = new FileStream(filePath, FileMode.Create, FileAccess.Write);//创建写入文件
StreamWriter sw = new StreamWriter(fs1);
sw.WriteLine(fileContent);//开始写入值
sw.Close();
fs1.Close();
}
else
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Write);
StreamWriter sr = new StreamWriter(fs);
sr.WriteLine(fileContent);//开始写入值
sr.Close();
fs.Close();
}
// var bat = System.Threading.Thread.GetDomain().BaseDirectory + "temp.bat";
string path = filePath;
//string path = @"C:\sql0\EZHbozmZpC.bat";
string errMsg = string.Empty;
string output = ExcuteBatFile(path, ref errMsg);
textBox3.Text = output;
}