12 December 2011

C# Lesson 12 : While Iterations and Reading Data from a Text File

Learn a new type of iteration statement (while) and how to utilize the StreamReader class to stream data from a file to the Console window. Additionally, we learn how to add new files to our project, how to set properties of our file using the Properties window, and how to add a using statement as a means of resolving a class name referenced in our code to the namespace in which it is defined.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReadTextFileWhile
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader myReader = new StreamReader("Values.txt");
            string line = "";

            while (line != null)
            {
                line = myReader.ReadLine();
                if (line != null)
                    Console.WriteLine(line);
            }

            myReader.Close();
            Console.ReadLine();

        }
    }
}
Source : MS Virtual Academy
Post a Comment