C# WinForms 进程编码问题

发布于 2024-12-07 03:58:08 字数 688 浏览 4 评论 0原文

我正在用 C# 编写一个 Windows 窗体应用程序 我有一个进程对象,它运行 cmd 命令并返回其输出。

Process Pro = new Process();
Pro.StartInfo.FileName = "cmd.exe";
Pro.StartInfo.Arguments = "<Dos Command here>";
Pro.StartInfo.CreateNoWindow = true;
Pro.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Pro.StartInfo.RedirectStandardOutput = true;
Pro.StartInfo.UseShellExecute = false;
Pro.Start();

效果很好!但是,如果命令的输出不是 ASCII(在我的例子中是希腊语),则输出是随机符号。肯定是编码问题。 如果我在控制台应用程序上运行相同的代码,一切都会顺利进行。

我尝试将基本流读取为 UTF-8,但没有成功!

System.IO.StreamReader Rdr = new System.IO.StreamReader(Pro.StandardOutput.BaseStream, Encoding.UTF8);

有没有办法在 winform 应用程序中正确读取输出? 谢谢!

I am writing a windows forms application in C#
I have a Process Object which runs a cmd command and returns it's output.

Process Pro = new Process();
Pro.StartInfo.FileName = "cmd.exe";
Pro.StartInfo.Arguments = "<Dos Command here>";
Pro.StartInfo.CreateNoWindow = true;
Pro.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Pro.StartInfo.RedirectStandardOutput = true;
Pro.StartInfo.UseShellExecute = false;
Pro.Start();

Which works fine! However if the output of the command is not ASCII(in my case Greek), the Output are random symbols. Surely an encoding problem.
If i run the same code on a console application everything runs smoothly.

I tried reading the Base stream as UTF-8, but no luck!

System.IO.StreamReader Rdr = new System.IO.StreamReader(Pro.StandardOutput.BaseStream, Encoding.UTF8);

Is there any way to read the output properly in a winform application?
Thnx!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我一直都在从未离去 2024-12-14 03:58:08

真正的解决方案是基于此:
unicode-characters-in-windows-command-line-how
检查这里:
Wiki 代码页
获取您需要的代码页。

你还可以做一个丑陋的黑客,将命令写入批处理文件(fe foo.bat)
然后将其运行为 foo.bat >日志.txt
然后您可以从 log.txt 读取输出。

The real solution is base on this:
unicode-characters-in-windows-command-line-how
check here:
Wiki code page
for the code page you need.

you can also do an ugly hack, writing the command to a batch file (f.e foo.bat)
then running it as foo.bat > log.txt
then you can read the output from log.txt.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文