CustomScript

2015年11月4日水曜日

[C#] Processの標準出力が文字化けする時の対処

  • C#
  • .Net 4.5
外部コマンドを実行するには System.Diagnostics.Process を使うのですが、その標準出力を StandardOutput.ReadToEnd() でリダイレクトすると文字化けしてしまう時があります。そんな時は StartInfo.StandardOutputEncoding に標準出力の文字コードを設定します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// サンプル
using (var process = new System.Diagnostics.Process())
{
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.CreateNoWindow = true;
 
    process.StartInfo.RedirectStandardOutput = true; // 標準出力リダイレクトON
    process.StartInfo.StandardOutputEncoding = Encoding.UTF8; // エンコーディング設定
 
    process.StartInfo.FileName = ... ;
    process.StartInfo.Arguments = ... ;
 
    process.Start();
 
    process.WaitForExit();
 
    string text = process.StandardOutput.ReadToEnd(); // 標準出力を得る
    :
}

0 件のコメント:

コメントを投稿