C# Simplified, part 5: Error Handling and Files - Reading from a file
(Page 7 of 8 )
You can read the contents of a file using the StreamReader class. The file name should be passed as a parameter to the OpenText() method of the File class. A loop is then created to read the file using the ReadLine() method, and the output is printed on to the console. The code in listing 5.10 helps you to understand the process in detail.
Listing 5.10
using System;
using System.IO;
class ReadFile
{
public static void Main()
{
Console.WriteLine("Reading the contents....");
try
{
StreamReader sr = File.OpenText("G:\\Demo.txt");
string readfile = null;
while ((readfile = sr.ReadLine()) != null)
{
Console.WriteLine(readfile);
}
}
catch
{
Console.WriteLine("The specified file dosen't exist");
Console.WriteLine("Please try again by changing the file name");
}
}
}
In the above code, a necessary exception is handled by using a try-catch block. Hence the program will show errors if you pass an invalid error name or a file name which does not exist.
Writing to a file
Like the StreamReader class, .NET Framework also provides the StreamWriter class, with which you can write content to a file. It is not necessary for you to create a file before writing content to it. C# automatically creates the file while executing the application. In listing 5.11, three lines of text are written to a file named WriteDemo.txt. The file name is passed as a parameter to an instance of FileInfo class. Then an instance of StreamWriter is created using the CreateText() method of FileInfo class. A series of statements are printed to the file using the WriteLine() method of StreamWriter class. Fnally, the file stream is closed with the help of Close() method.
Listing 5.11
using System;
using System.IO;
class WriteFile
{
public static void Main()
{
FileInfo fi = new FileInfo("D:\\WriteDemo.txt");
StreamWriter sw = fi.CreateText();
sw.WriteLine("Welcome");
sw.WriteLine("To");
sw.WriteLine("C-Sharp");
sw.Write(sw.NewLine);
Console.WriteLine("Please open the file to view the contents");
sw.Close();
}
}
Next: Copying a file >>
More C# Articles
More By Anand Narayanaswamy