Search code examples
c#.netencodingutf-8process

Encoding problem of Process.StandardInput or application executed from C# code


I have an issue with encoding of Process.StandartInput encoding. I am using some process in my Windows Form application but input should be UTF-8. Process.StandardInput.Encoding is read only so I can't set it to UTF-8 and it gets Windows default encoding which deteriorate native characters which are good in UTF-8. Two processes are used in the program: one writes output to a file and other reads. Since I can set up output encoding to UTF-8 that part is working properly but reading back is the part where I am having problems. I'll include the part where I use the process.

ProcessStartInfo info = new ProcessStartInfo("mysql");
info.RedirectStandardInput = true;
info.RedirectStandardOutput = false;
info.Arguments = mysqldumpstring;
info.UseShellExecute = false;
info.CreateNoWindow = true;
Process p1 = new Process();
p1.StartInfo = info;
p1.Start();
string res = file.ReadToEnd();
file.Close();

// where encoding should be Encoding.UTF8;
MessageBox.Show(p1.StandardInput.Encoding.EncodingName); 

p1.StandardInput.WriteLine(res);
p1.Close(); 

Solution

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