Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
like image 790
Mustafa Avatar asked May 18 '10 08:05

Mustafa


2 Answers

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();
like image 55
Victor Avatar answered Sep 23 '22 23:09

Victor


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.

like image 25
Brendon Avatar answered Sep 22 '22 23:09

Brendon