+92 332 4229 857 99ProjectIdeas@Gmail.com

File Reading (C#.net)


Reading a File:
The following code shows you how to read from file, for reading a file you will have to include namespace System.IO which contains all the classes and functions.


Code


Way One:

using System.IO;


  public class DrivesInfo 

   {
       public static void Main(string[] args) 
       
       {
          TextReader tw = File.OpenText(@"d:\Osama_Stuff\Billy.txt");
          
          try
            {
               
                //Reading all file data without loop
                Console.WriteLine(tw.ReadToEnd());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                tw.Close();
            }

       }
}

Way Second:

try
   {

   FileStream fs = new FileStream(@"D:\Osama_Stuff\abc1.txt", FileMode.Open, FileAccess.Read);
      
   StreamReader sw = new StreamReader(fs);

       while (sw.ReadLine() != null)
       {
          Console.WriteLine(sw.ReadLine());          
       }
               
      //Or you can use without loop like:
       Console.WriteLine(sw.ReadToEnd());
  }
   catch (Exception ex)
  {
        Console.WriteLine(ex.ToString());

  }

0 comments: