Simple C# Question Reading a file line by line

  • Thread starter Thread starter Bill Uliv
  • Start date Start date
B

Bill Uliv

Guest
I copied line for line out of the C# For Dummies Book. ( pages 450-451)

The end game, is to open a comma delimited file, but I am trying to learn C#. The code I have below is what I entered, but I can not figure out whats wrong with it. I dont even understand the error messages. I got it down from 16 errors to 2, so any help would be appreciated.

using System;

using System.IO;
using System.IO.StreamReader;

namespace FileRead

{
public class Program
{
public static void Main(string[] args)

{

// You need a file reader object

StreamReader sr = null;
string fileName = " ";

try

{
// Get a fileName from the user

sr = GetReaderForFile (fileName);

// Read the contents of the file.

ReadFileToConsole (sr);
}

catch (IOException ioErr)
{

Console.WriteLine(" {0} \n\n", ioErr.Message);
}

finally // Clean up
{
if (sr != null) // Guard against trying to close () a null object
{
sr.Close(); //Take care of flush as well
sr=null;
}
}

Console.WriteLine (" Press Enter to Termintae... " );
Console.Read();

}

public void GetReaderForFile (string fileName)
{
StreamReader sr;

Console.Write ("Enter the name of the file to read ");

fileName=Console.ReadLine();

// User didnt enter anything; throw an exception
// to indicate that this is not acceptable

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;}

// ReadFileTo COnsole by sr and write them out to console

private static void ReadFileToConsole(StreamReader sr)

{

Console.WriteLine( " \nContents of file");

//Read one libe at a time
while (true)

{

//Read Line
string input = sr.ReadLine ();

// Quit when you dont get anything back
if (input==null)
{
break;


}

// Write whatever you read to the console

Console.WriteLine (input);

}


}
}
}

Continue reading...
 
Back
Top