たるきちのあれこれ









  Topプログラミングサンプル ▶ ファイルの書き込み、読み込み

ファイル書き込みのサンプルです。

C#  ファイル書き込み

// using System.IO;

using (StreamWriter sw = new StreamWriter(@"C:\sample.txt", false, Encoding.GetEncoding("Shift_JIS")))
{
    sw.Write("abcdefg\r\n");
}



ファイル読み込みのサンプルです。

C#  ファイル読み込み

// using System.IO;

string str;

// ファイルを先頭から最後まで読み込む
using (StreamReader sr1 = new StreamReader(@"C:\sample.txt", Encoding.GetEncoding("Shift_JIS")))
{
    str = sr1.ReadToEnd();
}

// ファイルを1行ずつ読み込む
using (StreamReader sr2 = new StreamReader(@"C:\sample.txt", Encoding.GetEncoding("Shift_JIS")))
{
    while (sr2.Peek() > -1)
    {
        Application.DoEvents();
        str = sr2.ReadLine();
    }
}