+92 332 4229 857 99ProjectIdeas@Gmail.com

File Writing (C#.net)


Writing in File:   
The namespace for writing a data in file is System.IO which contains built-in classes and functions to handle files.

Code
Way One:

using System.IO;

public class WritingFile

{
    public static void Main(string[] args) 
       
      {
        
            TextWriter tw = File.CreateText(@"d:\Osama_Stuff\Billy.txt");
           
          try
            {
                String writeText = Console.ReadLine();
                tw.WriteLine(writeText);
                tw.Flush(); // To send data from stream to file
              
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                tw.Close();
            }
      
      }
}

Way Second:

try

  {

   FileStream fs = new FileStream("abc1.txt", FileMode.Create, FileAccess.Write);

   StreamWriter sw = new StreamWriter(fs);
   sw.WriteLine("I am osama mursleen");
   sw.Flush(); 

  }

  catch (Exception ex)
  
  {
     Console.WriteLine(ex.Message);
  
  }

Appending Data In File:

try

  {

   FileStream fs = new FileStream("abc1.txt", FileMode.Append, FileAccess.Write);

   StreamWriter sw = new StreamWriter(fs);
   sw.WriteLine("I am osama mursleen");
   sw.Flush(); 

 }

  catch (Exception ex)
  
  {
     Console.WriteLine(ex.Message);
  
  }

0 comments: