The System.IO Namespace


To see how to work with files in .NET, and to see how easily we can catch exceptions thrown by another .NET language, we'll now use the Stream- Reader and File classes from the System.IO namespace to build a simple "type" program that displays text files, screen by screen, in the console window.

The File class provides various methods for working with files, including the static Exists method, which can be used to test whether or not a file exists.

The System.IO namespace provides the StreamReader class to read data from text files, and the StreamWriter class to write data to text files. Reading text files with the StreamReader class is extremely easy: After you open the file by calling the StreamReader's contructor, you read the file by calling the ReadLine() method until it returns an empty string (a null object).

When you're done with the StreamReader object, you'll need to destroy it manually because the StreamReader class uses resources that should be released as soon as possible. .NET classes that allocate resources always provide Close() or Dispose() methods for releasing these resources when you're done using them. The StreamReader class, for instance, provides the Close() method, which then calls Dispose() internally to free the stream used by the StreamReader class.

Listing 29-21, which follows, shows the entire source of a C# class library, which uses the System.IO.File and System.IO.StreamReader classes to implement the functionality of the command prompt's "type" command. The DisplayFile() method either throws the System.IO.FileNotFound- Exception exception if the file is not found or instantiates the StreamReader class and displays the contents of the file if the file exists.

Listing 29-21: Reading text files with the StreamReader class

image from book
using System; using System.IO; namespace Wordware.IOLibrary {    public class TextFileReader    {       public static void DisplayFile(string FileName)       {         if(!File.Exists(FileName))         {            // pass the message to the Message property            // pass the file name to the FileName property            throw new FileNotFoundException("File not found!",               FileName);         }         string line;         int counter = 1;         StreamReader sr = new StreamReader(@FileName);         try         {            line = sr.ReadLine();            while(line != null)            {               Console.WriteLine(line);               // stop after the screen is filled               if(counter == 24)               {                  Console.WriteLine("-- More --");                  Console.ReadLine();                  counter = 1;               }       // if (counter)               line = sr.ReadLine();               counter++;            }     // while         }         finally         {            sr.Close();      // close the StreamReader         }       }       public TextFileReader()       {         // constructor does nothing       }    } }
image from book

If you've read the code carefully, you've undoubtedly noticed the @ operator in front of the FileName string passed to the StreamReader's constructor:

StreamReader sr = new StreamReader(@FileName);

By default, C# strings support escape sequences (\\, \n, etc.), and thus file names like "c:\Folder\SubFolder\Data.txt" aren't properly interpreted. The proper way to write this path in C# is "c:\\Folder\\SubFolder\\Data.txt." However, by using the @ operator in front of the string, you can disable escape sequence processing, and thus you can write file paths normally, i.e., @"C:\Folder\SubFolder\Data.txt."

To use the Wordware.IOLibrary.TextFileReader class, create a new Delphi for .NET console application and add the reference to the library. To display a text file using the TextFileReader class, you need to call the DisplayFile method, preferably in a try block, and display an error message if you catch the System.IO.FileNotFoundException exception.

Listing 29-22 shows the source code of a Delphi for .NET console application that uses the Wordware.IOLibrary.TextFileReader class. Figure 29-14, which follows the listing, shows how the TextFileReader class displays text files.

image from book
Figure 29-14: Displaying text files with the Wordware.IOLibrary.TextFileReader class

Listing 29-22: Using the Wordware.IOLibrary.TextFileReader class to view text files

image from book
program Project1; {$APPTYPE CONSOLE} {%DelphiDotNetAssemblyCompiler '..\io_library\bin\debug\io_library.dll'} uses System.IO, Wordware.IOLibrary; const   FNAME: string = 'C:\My Components\PDFExport.pas'; begin   try     TextFileReader.DisplayFile(FNAME);   except     // catch the exception thrown in a C# class library     on e: System.IO.FileNotFoundException do     begin       Console.WriteLine('File "{0}" does not exist!', e.FileName);       Console.WriteLine;     end;      // on Exception   end;        // try   Console.WriteLine;   Console.WriteLine('Press any key to continue...');   Console.ReadLine(); end.
image from book



Inside Delphi 2006
Inside Delphi 2006 (Wordware Delphi Developers Library)
ISBN: 1598220039
EAN: 2147483647
Year: 2004
Pages: 212
Authors: Ivan Hladni

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net