Use using statement to manage resource in CSharp

Description

The following code shows how to use using statement to manage resource.

Example


using System;              
using System.IO;/*from   ww  w  .ja  va 2s .c o m*/

class MainClass
{
   static void Main()
   {
      using (TextWriter tw = File.CreateText("test.txt"))// using statement 
      {
         tw.WriteLine("string");
      }

      using (TextReader tr = File.OpenText("test.txt"))
      {
         string str;
         while (null != (str = tr.ReadLine()))
            Console.WriteLine(str);
      }
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception