Use Using statement to deal with multiple resources in CSharp

Description

The following code shows how to use Using statement to deal with multiple resources.

Example


         /*from   w  w  w. j  ava 2 s  .  c o  m*/

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;             

class MainClass
{
   static void Main()
   {
      using (TextWriter tw1 = File.CreateText("test.txt"),
                        tw2 = File.CreateText("test2.txt"))
      {
         tw1.WriteLine("test");
         tw2.WriteLine("test1");
      }

      using (TextReader tr1 = File.OpenText("test.txt"),
                        tr2 = File.OpenText("test2.txt"))
      {
         string str;
         while (null != (str = tr1.ReadLine()))
            Console.WriteLine(str);
            
         while (null != (str = tr2.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