2009年12月12日土曜日

finallyの代わりにusing statementを使用しファイル操作でエラーがでても、確実にファイルを閉じる。
using System;
using System.IO;


class MainClass
{
    static void Main()
    {
        try
        {
            // ファイルを開く
            using (StreamReader sr = new StreamReader("sample.text",
                System.Text.Encoding.Default))
            {
                // ファイルの内容を読み込む
                string text = sr.ReadToEnd();


                // 読み込んだ内容を出力
                Console.Write(text);
            }
        }
        catch (Exception error)
        {
            // エラーの原因の詳細情報を出力
            Console.WriteLine(error.Message);
        }
    }
}

0 コメント:

コメントを投稿