process.standardInput encoding problem

点点圈 提交于 2019-11-29 01:24:56

Using of StreamWriter created the next way (instead of StandardInput) gives desired result:

StreamWriter utf8Writer = new StreamWriter(proc.StandardInput.BaseStream, Encoding.UTF8);
utf8Writer.Write(...);
utf8Writer.Close();

I've just encountered this problem and was unable to use the Console.InputEncoding technique because it only seems to work in console applications.

Because of this I tried Victor's answer, however I encountered the same issue as the commenter MvanGeest where by the BOM was still being added. After a while I discovered that it is possible to create a new instance of UTF8Encoding that has the BOM disabled, doing this stops the BOM from being written. Here is a modified version of Victor's example showing the change.

StreamWriter utf8Writer = new StreamWriter(proc.StandardInput.BaseStream, new UTF8Encoding(false));
utf8Writer.Write(...);
utf8Writer.Close();

Hope this saves someone some time.

Another solution is to set the Console InputEncoding before you create the process.

Console.InputEncoding = Encoding.UTF8;

got it working now set my application output type to console application and managed to hide the console window appears before the forms. It basically works like normal only when program run, a console windows pops and hides.

static class Program
{
    [DllImport("kernel32.dll")]
    static extern bool AttachConsole(int dwProcessId);
    private const int ATTACH_PARENT_PROCESS = -1;

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool SetConsoleCP(
         uint wCodePageID
         );

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern uint GetConsoleCP();

    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Console.Title = "Stok";
        // redirect console output to parent process;
        // must be before any calls to Console.WriteLine()
        AttachConsole(ATTACH_PARENT_PROCESS);
        System.Console.InputEncoding = Encoding.UTF8;

        IntPtr hWnd = FindWindow(null, "Stok"); //put your console window caption here

        if (hWnd != IntPtr.Zero)
        {
            //Hide the window
            ShowWindow(hWnd, 0); // 0 = SW_HIDE
        }

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