.Net Framework C#

C# using ステートメントを利用したリソースの読み込みと開放の例

2017年5月18日

using ステートメントを利用することで読み込むリソースを必ず開放してくれます。using ステートメントで読み込むオブジェクトは、IDisposable インターフェイスを実装している必要があります。

private void button1_Click(object sender, EventArgs e)
{
    var file1 = new FileInfo("TextFile1.txt");
    using(var streamReader = file1.OpenText())
    {
        string textLine;
        while ((textLine = streamReader.ReadLine()) != null)
        {
            System.Diagnostics.Debug.WriteLine(textLine);
        }
    }
}

オブジェクトが IDisposable インターフェイスを実装していないと、ビルドエラーになります。

リンク:
C# プログラミング

-.Net Framework, C#