DevPinoy.org
A Filipino Developers Community
   
How To: Read a file in .NET - Sample 2
Sample demonstrates how to use the File.ReadAllLines technique 

[C# Version]

using System;
using System.IO;

namespace KeithRull.ReadMyFile
{
    class Program
    {
        static void Main(string[] args)
        {
            //the filename of the file to read
            string xmlFilename = "Symbols.xml";
          
            //validate if the file exist
            if (File.Exists(xmlFilename))
            {
                //read the contents of the file
                string[] fileContent = File.ReadAllLines(xmlFilename);

                //iterate for each line item in our file
                foreach (string lineItem in fileContent)
                {
                    //display the output in the screen
                    Console.WriteLine(lineItem);
                }
            }
            else
            {
                //notify that the file was not found
                Console.WriteLine("File not found!");
            }

            //pause and wait for the user.
            Console.ReadLine();
        }
    }
}

[VB.NET Version]

Imports System
Imports System.IO

Namespace KeithRull.ReadMyFile
    Class Program
        Private Shared Sub Main(ByVal args As String())
            'the filename of the file to read
            Dim xmlFilename As String = "Symbols.xml"
           
            'validate if the file exist
            If File.Exists(xmlFilename) Then
                'read the contents of the file
                Dim fileContent As String() = File.ReadAllLines(xmlFilename)
               
                'iterate for each line item in our file
                For Each lineItem As String In fileContent
                    'display the output in the screen
                    Console.WriteLine(lineItem)
                Next
            Else
                'notify that the file was not found
                Console.WriteLine("File not found!")
            End If
           
            'pause and wait for the user.
            Console.ReadLine()
        End Sub
    End Class
End Namespace


Posted 03-19-2008 12:12 PM by keithrull
Copyright DevPinoy 2005-2008