Page 1 of 1

System.IO in C# Part 1.5

#1 PsychoCoder   User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1663
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Posted 03 September 2007 - 04:26 PM

Next to ReadLine, ReadToEnd is the most commonly used method of the TextReader Class. As the name implies, it reads the entire file at once, no need to use Peek or a loop. Lets take a look at an example employing this member:

/// <summary>
/// Method for reading an entire file at once
/// </summary>
/// <param name="file">File to read</param>
/// <returns>File contents in a string</returns>
public static string ReadEntireFile(string file)
{
	//create a string variable to hold the contents of the file
	string fileContents = string.Empty;
	//always use a try...catch to deal 
	//with any exceptions that may occur
	try
	{
		//create a new TextReader and open our file
		using (TextReader reader = new StreamReader(file))
		{
			//now read the entire file at once into our variable
			fileContents = reader.ReadToEnd().ToString();
		}
		return fileContents;
	}
	catch (Exception ex)
	{
		//deal with any errors
		Console.WriteLine(ex.Message);
		return fileContents;
	}
}



As in the previous example, we create our string variable fileContents to hold the contents of the file, we create our TextReader object using the Using Statement, but unlike before, we don't use a loop. In this example we use ReadToEnd to read the entire file on one pass. Both approaches, as with any programming approach, have their pro's and con's.

NOTE: Always put your logic inside a Try...Catch block to catch and deal with any Exceptions that may have been raised during the process.

In the next example, lets look at reading from a specified line in a text file. In this example, we split the lines in the file into an array, then the user can pass an integer value representing which line they'd like to read.

/// <summary>
/// Method to read a specified line in a text file
/// </summary>
/// <param name="file">File to read from</param>
/// <param name="line">Line number to read</param>
/// <returns></returns>
public static string ReadSpecifiedLine(string file, int line)
{
	//create a variable to hold the contents of the file
	string fileContents = string.Empty;
	//create a variable to hold our line contents
	string lineContent = string.Empty;
	//always use a try...catch to deal 
	//with any exceptions that may occur
	try
	{
		using (StreamReader stream = new StreamReader(file))
		{
			fileContents = stream.ReadToEnd().Replace("\r\n", "\n").Replace("\n\r", "\n");
			string[] linesArray = fileContents.Split(new char[] { '\n' });
			lineContent = linesArray[line];
			return lineContent;
		}
	}
	catch (Exception ex)
	{
		//deal with any errors
		Console.WriteLine(ex.Message);
		return lineContent;
	}
}



As with the previous examples we create the string variable fileContents, our StreamReader Object, the difference here is we, as stated above, convert the lines in the file into a string array, then use the value passed by the user to read that specified line (using the value as the index of the array) and set the value of our variable to that line's value.

Lets take a look at once final Member of the System.IO.File Class, the Exists Member. This member allows us to check if the specified file exists prior to opening and manipulating it.

/// <summary>
/// Method for reading a file if it exists
/// </summary>
/// <param name="file">File to read</param>
/// <returns>File contents in a string</returns>
public static string ReadEntireFileIfExists(string file)
{
	//create a string variable to hold the contents of the file
	string fileContents = string.Empty;
	//always use a try...catch to deal 
	//with any exceptions that may occur
	try
	{
		//check to see if the file exists
		if (System.IO.File.Exists(file))
		{
			//create a new TextReader and open our file
			using (TextReader reader = new StreamReader(file))
			{
				//now read the entire file at once into our variable
				fileContents = reader.ReadToEnd();
			}
			return fileContents;
		}
		else
		{
			throw new FileNotFoundException(file + " could not be found");
		}
	}
	catch (Exception ex)
	{
		//handle your errors here
		Console.WriteLine(ex.Message);
		return fileContents;
	}			
}



Notice we use Exists to determine if the file actually exists prior to using it. If the file exists we go ahead and read the file, if the file doesn't exist we throw a FileNotFoundException letting the user know the file doesn't exist.

That is Part I of the System.IO in C# Tutorial. I hope you have found this tutorial helpful and useful. Thanks for reading :)

Continue to Part 2 of this tutorial

Is This A Good Question/Topic? 1
  • +

Replies To: System.IO in C# Part 1.5

#2 MoistFist   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 101
  • Joined: 02-June 09

Posted 29 September 2009 - 09:38 AM

Thanks for this, it has helped a lot, but my one question is if i am using this in a forms app. And put this in on a button click what do i need for it to fire when on event button click
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;


namespace CSharpPracticeForm
{
	public partial class TextReadForm1 : Form
	{
		public TextReadForm1()
		{
			InitializeComponent();
		}

		private void button1_Click(object sender, EventArgs e);
				   

			
			
			
			public static string ReadFileLineAtATime(string file)
{
	  ///create a string variable to hold the file contents
		 string fileContents = string.Empty;
		 //create a new TextReader then open the file
		 TextReader reader = new StreamReader(file);
		  //loop through the entire file
		  while (reader.Peek() != -1)
		  {
				//add each line to the fileContents variable
				fileContents += reader.ReadLine().ToString();
		  }
		  reader.Close();
		  //return the results
		  return fileContents;
}
			
			
			
			

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1