CSharp examples for File IO:Text File
Read a text file and write it out to the Console.
using System;/*from w ww . j a v a 2 s.c om*/ using System.IO; public class Program { public static void Main(string[] args) { StreamReader sr = null; string fileName = ""; try { sr = GetReaderForFile(fileName); ReadFileToConsole(sr); } catch (IOException ioErr) { Console.WriteLine("{0}\n\n", ioErr.Message); } finally { if (sr != null) { sr.Close(); sr = null; } } } private static StreamReader GetReaderForFile(string fileName) { StreamReader sr; Console.Write("Enter the name of a text file to read:"); fileName = Console.ReadLine(); if (fileName.Length == 0) { throw new IOException("You need to enter a filename."); } FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read); sr = new StreamReader(fs, true); return sr; } private static void ReadFileToConsole(StreamReader sr) { while (true) { string input = sr.ReadLine(); if (input == null) { break; } Console.WriteLine(input); } } }