Menu
Coddy logo textTech

Using vs. Try-Finally

CoddyのC#ジャーニー「ロジックとフロー」セクションの一部 — レッスン 28/66。

using ステートメントと try-finally ブロックはどちらも、適切に破棄する必要があるリソースの管理に役立ちます。using ステートメントは、IDisposable オブジェクトが確実に適切にクリーンアップされるようにするための、よりクリーンで簡潔な方法を提供します。

注: using は破棄のための try-finally パターンを置き換えるものであり、try-catch を置き換えるものではありません。例外を処理するために、依然として using ブロックを try-catch 内にラップすることができます。

まずは、try-finally アプローチを見てみましょう:

StreamReader reader = null;
try
{
    reader = new StreamReader("file.txt");
    string content = reader.ReadToEnd();
    Console.WriteLine(content);
}
finally
{
    if (reader != null)
    {
        reader.Dispose();
    }
}

using ステートメントは、このコードを簡略化します:

using (StreamReader reader = new StreamReader("file.txt"))
{
    string content = reader.ReadToEnd();
    Console.WriteLine(content);
}

using ステートメントは、例外が発生した場合でも、ブロックが終了したときに自動的に Dispose() を呼び出します。

StreamReaderとは何ですか?
StreamReader は、ファイルからテキストを読み取るために使用されるクラスです。ファイル名を渡すことで作成し、読み取り用にファイルを開きます。これは IDisposable を実装しているため、使用後は適切に閉じる必要があります。これはまさに using が自動で行ってくれることです。

一般的な StreamReader メソッド:

  • ReadToEnd() — ファイル全体を単一の文字列として読み取ります
  • ReadLine() — 一度に1行ずつ読み取り、ファイルの終わりに達すると null を返します

ファイル内の行数をカウントするには、ReadLine() ループを使用できます。

using (StreamReader reader = new StreamReader("file.txt"))
{
    int lineCount = 0;
    while (reader.ReadLine() != null)
    {
        lineCount++;
    }
    Console.WriteLine(lineCount);
}

また、usingtry-catch を組み合わせて、ファイルが見つからないなどの例外を処理することもできます:

try
{
    using (StreamReader reader = new StreamReader("file.txt"))
    {
        int lineCount = 0;
        while (reader.ReadLine() != null)
        {
            lineCount++;
        }
        Console.WriteLine(lineCount);
    }
}
catch (FileNotFoundException)
{
    Console.WriteLine("File not found");
}
challenge icon

チャレンジ

簡単

processFile という名前のメソッドを作成し、以下の処理を実装してください:

  1. ファイル名を文字列のパラメータとして受け取ります
  2. StreamReaderusing ステートメントを使用して、ファイルからすべての行を読み取ります
  3. ファイルの行数を返します
  4. FileNotFoundException が発生した場合は、"File not found" と出力し、-1 を返します

自分で試してみよう

using System;
using System.IO;

class ProcessFile
{
    public static int processFile(string filename)
    {
        // ここにコードを書いてください
    }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

ロジックとフローのすべてのレッスン