2009年12月12日土曜日

いよいよStreamWriterクラスとWriteLineメソッドを使用しファイルを作成し、StreamReadクラスとReadLineメソッドを使用しファイルを読み込み、そしてファイル内容を1行ずつ出力する。
using System;
using System.IO;


class MainClass
{
    // ファイルに書き込み
    static void write(string name)
    {
        using (var sw = new StreamWriter(
            name, false, System.Text.Encoding.Default))
        {
            // 1行ずつ書き込む
            sw.WriteLine("sample");
            sw.WriteLine("サンプル");
            sw.WriteLine("Kamimura");
        }
    }


    // ファイルを読み込む
    static void read(string name)
    {
        using (StreamReader sr = new StreamReader(
            name, System.Text.Encoding.Default))
        {
            // 1行ずつ読み込む
            string line = "";
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }


    static void Main()
    {
        try{
            string name="sample.txt";


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


            // ファイルを読み込む
            read(name);
        }
        catch(Exception error)
        {
            Console.WriteLine(error.Message);
        }
    }
}


0 コメント:

コメントを投稿