从.NET开始进程但RedirectedStandardOutput不支持UTF-8

时间:2009-02-10 02:23:38

标签: .net process utf-8 streamwriter

我试图使用以下代码从.NET调用php的HTML净化器:

    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();

..并且所有工作都很好,除了......我无法找回非asci字符。例如,在输入中提供一些韩文字符会将问号作为输出返回。

即使HTMLPurifier函数是伪造的,我也会发生这种情况,我只是想简单地提供输入.NET,将它存储在php变量中,然后将该变量回送给输出。

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

感谢指针。我确实设法解决了它。捕获是为BOTH输入和输出明确指定UTF-8。最后,woking代码如下所示:

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();

答案 1 :(得分:2)

尝试

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