こんなコードで実験
ファイルへ文字列を書き込んで、読み込んでいます。
string fileContents = "c#でファイル読み書きサンプル";
// ファイル書き込み
using (StreamReader sr = new StreamReader(sourcePath, System.Text.Encoding.GetEncoding("shift_jis")))
//using (StreamReader sr = new StreamReader(sourcePath, System.Text.Encoding.GetEncoding("ASCII")))
//using (StreamReader sr = new StreamReader(sourcePath)) // UTF-8 で書き出される
{
fileContents = sr.ReadToEnd();
}
// ファイル読み込み
using (StreamWriter sr = new StreamWriter(destPath, false, System.Text.Encoding.GetEncoding("shift_jis")))
//using (StreamWriter sr = new StreamWriter(destPath)) // UTF8 で読み出される
{
sr.Write(fileContents);
}
ファイルを読み込むときは読み込み対象の文字コードに合わせないといけない(デフォルトUTF8)
ファイルを書き出すときは指定した文字コードにて書き出される(デフォルトUTF8)
当たり前といえば当たり前なんですが知っていないとちょっと焦るかもしれません。
sjis周りの文字化けについてはあえて触れないことにします。
見るならこのあたり?
http://www.kent-web.com/pubc/garble.html