Started Process from .NET but RedirectedStandardOutput doesn't support UTF-8

喜你入骨 提交于 2019-12-11 08:38:41

问题


I am trying to call php's HTML purifier from .NET using this code:

    Process myProcess = new Process();

    myProcess.StartInfo.FileName = "C:\Path\to\php.exe";
    myProcess.StartInfo.Arguments = "C:\Path\to\purify.php";
    myProcess.StartInfo.UseShellExecute = false;
    myProcess.StartInfo.RedirectStandardOutput = true;
    myProcess.StartInfo.RedirectStandardInput = true;

    myProcess.Start();

    StreamWriter myStreamWriter = myProcess.StandardInput;

    String inputText;

    inputText = txtCodes.Text;
    if (inputText.Length > 0)
    {
        myStreamWriter.Write(inputText);
    }
   myStreamWriter.Close();

    labMsg.Text = myProcess.StandardOutput.ReadToEnd();

    myProcess.WaitForExit();

    myProcess.Close();

.. and all works fine except ... I am not able to get back non-asci characters. For example providing some Korean characters in the input returns questionmarks as output.

This happens even if the HTMLPurifier function is bypased and I am just trying to simple provide the input .NET, store it in php variable, and echo that variable back to output.

Any ideas?


回答1:


Thanks for the pointer. I did actually managed to solve it. The catch was to explicitly specify UTF-8 for BOTH input and Output. In the end the woking code looks like this:

Process myProcess = new Process();

    myProcess.StartInfo.FileName = "C:\Path\to\php.exe";
    myProcess.StartInfo.Arguments = "C:\Path\to\purify.php";

    myProcess.StartInfo.UseShellExecute = false;
    myProcess.StartInfo.RedirectStandardOutput = true;
    myProcess.StartInfo.RedirectStandardInput = true;
    myProcess.StartInfo.StandardOutputEncoding = Encoding.UTF8;

    myProcess.Start();
    StreamWriter myStreamWriter = new StreamWriter(myProcess.StandardInput.BaseStream, Encoding.UTF8);

    String inputText;
    inputText = txtCodes.Text;

    if (inputText.Length > 0)
    {
        myStreamWriter.Write(inputText);
    }

    myStreamWriter.Close();

    labMsg.Text = myProcess.StandardOutput.ReadToEnd();


    myProcess.WaitForExit();

    myProcess.Close();



回答2:


Try

myProcess.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;


来源:https://stackoverflow.com/questions/530882/started-process-from-net-but-redirectedstandardoutput-doesnt-support-utf-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!