C# School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a C# Expert!

Join 307,084 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 2,265 people online right now. Registration is fast and FREE... Join Now!




System.IO in C# Part 1.5

 
Reply to this topicStart new topic

> System.IO in C# Part 1.5

PsychoCoder
Group Icon



post 3 Sep, 2007 - 03:26 PM
Post #1


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:

CODE

/// <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.

CODE

/// <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.

CODE

/// <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 smile.gif

Continue to Part 2 of this tutorial
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

MoistFist
**



post 29 Sep, 2009 - 08:38 AM
Post #2
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
CODE


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


Go to the top of the page
+Quote Post


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/21/09 10:41AM

Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month