美文网首页
C#捕捉外部程序的错误

C#捕捉外部程序的错误

作者: xigua1234 | 来源:发表于2018-01-05 15:12 被阅读156次

1.调用

        // 用于调用外部exe
        public string StartProcess(string runFilePath, params string[] args)
        {
            try
            {
                string s = "";
                foreach (string arg in args)
                {
                    s = s + arg + " ";
                }
                s = s.Trim();
                Process process = new Process();//创建进程对象    
                ProcessStartInfo startInfo = new ProcessStartInfo(runFilePath, s); // 括号里是(程序名,参数)
                process.StartInfo = startInfo;
                process.StartInfo.UseShellExecute = false;   //是否使用操作系统的shell启动,设为false后才能捕捉错误
                startInfo.RedirectStandardOutput = true;     //由调用程序获取输出信息
                startInfo.CreateNoWindow = true;             //不显示调用程序的窗口
                process.StartInfo.RedirectStandardError = true;  //重定向错误流
                startInfo.StandardErrorEncoding = ASCIIEncoding.UTF8; // 设置编码
                startInfo.StandardOutputEncoding = ASCIIEncoding.UTF8;
                process.Start();
                StreamReader myStreamReader = process.StandardError;// 读取错误流
                string feedback_all = myStreamReader.ReadToEnd();
                string feedback = myStreamReader.ReadLine();
        process.WaitForExit();
                return "参数:\n"+s+"\n捕捉到外部程序的错误:\n" + feedback_all;
            }
            catch (System.SystemException e)
            {
                return "捕捉到C#的错误:\n" + e.ToString();
            }

        }

        }
        // 打开"查询列表.csv",批量采集
        public void batch_crawl(object sender, EventArgs e)
        {
            string[]  lines =File.ReadAllLines(@"价格采集.exe",Encoding.UTF8);// 读取
            for (int i = 1; i <= 1; i = i + 1) // 测试
            {
                string cc = StartProcess(exe_path, data);
                MessageBox.Show(cc.ToString());
            }
        }
    }

2.编码问题

图片.png
                startInfo.StandardErrorEncoding = ASCIIEncoding.UTF8; // 设置编码
                startInfo.StandardOutputEncoding = ASCIIEncoding.GetEncoding(936);// gbk只能用代码页来设置

改一下,编码,变成另外一个地方乱码


图片.png
                startInfo.StandardErrorEncoding = ASCIIEncoding.GetEncoding(936); // 设置编码
                startInfo.StandardOutputEncoding = ASCIIEncoding.GetEncoding(936);// gbk只能用代码页来设置

这种问题,应该是你被调用exe的源代码、现在的C#编码不一致,所以这里的编码怎么设置都有一个会乱码

相关文章

网友评论

      本文标题:C#捕捉外部程序的错误

      本文链接:https://www.haomeiwen.com/subject/eghsnxtx.html