0
点赞
收藏
分享

微信扫一扫

c#执行bat批处理文件并回显执行结果

醉倾城1 2022-04-15 阅读 98
c#

研究了好几个小时才搞定

函数体

       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.
|||||

举报

相关推荐

0 条评论