C# read from file

To read text from a text file, you will create an FileStream object then wrap this object in the StreamReader object and use ReadLine method to read text line by line or use ReadToEnd method to read all text in the file at once.

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

namespace Csharp
{

   class ProgramReadfromFile
   {


     static void Main(string[] args)
     {

        FileInfo f = new FileInfo("D:\\file.txt");

        if (!f.Exists)
        {
           Console.WriteLine("The file does not exist.");


        }
        else
        {
           //create FileStream object
           FileStream fs = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
           //Wrap the filestream object in StreamReader object
           StreamReader sr = new StreamReader(fs);
           String text = "";
           while ((text = sr.ReadLine()) != null)
           {
             Console.WriteLine(text);
            
           }
           sr.Close();
        }
              
        Console.Read();

     }
   }
}

Posted by: Dara | post date: 01-31-2013 | Subject: C# Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.