2009年12月13日日曜日

StriamWriterの2つ目のパラメータをfalseではなくtrueにして、ファイルを上書きするのではなく末尾に1行ずつ書き込んでみる。
using System;
using System.IO;


class MainClass
{
    static void write(string name)
    {
        using (var sw = new StreamWriter(name, true,
            System.Text.Encoding.Default))
        {
            // 1行ずつ書き込む
            sw.WriteLine("Sample1");
            sw.WriteLine("Sample2");
            sw.WriteLine("サンプル1");
            sw.WriteLine("サンプル2");
            sw.WriteLine("Kamimura");
        }
    }
    static void read(string name)
    {
        using (var sr = new StreamReader(name,
            System.Text.Encoding.Default))
        {
            string line = "";


            // nullになるまで1行ずつ読み込んで出力する
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }


    static void Main()
    {
        // 予期しない例外が起きた時のためにtry-catch
        try
        {
            string name = "sample.txt";


            // ファイルに書き込む
            write(name);


            // ファイルを読み込んで出力する
            read(name);
        }
        catch (Exception error)
        {
            // 例外の原因の詳細情報を表示する
            Console.WriteLine(error.Message);
        }
    }
}

0 コメント:

コメントを投稿