How To Write/Read A Text File In C#

Discussion in 'Programming' started by largn81, Jan 26, 2008.

  1. #1
    Hello:
    In this article: You will learn to Write or Read A Text File.

    Let's Begin:
    First Create a new project (ConsoleApp or WinApp).
    And Make sure your program uses these namespaces:



    Code: ( text )
    using System;
    using System.IO;
    using System.Diagnostics;



    Now, we will begin writing text to a file:
    1)- Create a new stream-writer and open the file:


    Code: ( text )
    TextWriter tw = new StreamWriter(@"C:\Hello.txt");



    2)- Write text to the file:


    Code: ( text )
    tw.WriteLine("Hello");



    3)- Close the file.


    Code: ( text )
    tw.Close();



    4)- Launch the file:


    Code: ( text )
    Process.Start(@"C:\Hello.txt");



    Here is all the code:

    Code: ( text )
    //Creating a new stream-writer and opening the file.
    TextWriter tsw = new StreamWriter(@"C:\Hello.txt");

    //Writing text to the file.
    tsw.WriteLine("Hello");

    //Close the file.
    tsw.Close();

    //Launch the file.
    Process.Start(@"C:\Hello.txt");

    Console.WriteLine("You're done, press any key to exit...");
    Console.ReadKey();

    Now, we will begin reading text from a file:
    1)- Creating a new stream-reader and opening the file:

    Code: ( text )
    TextReader trs = new StreamReader(@"C:\Hello.txt");


    2)- Reading text of the file:

    Code: ( text )
    //Reading all the text of the file.
    Console.WriteLine(trs.ReadToEnd());

    //Or Can Reading a line of the text file.
    //Console.WriteLine(trs.ReadLine());


    3)- Close the file:

    Code: ( text )
    trs.Close();


    Here is all the code:

    Code: ( text )
    //Creating a new stream-reader and opening the file.
    TextReader trs = new StreamReader(@"C:\Hello.txt");

    //Reading all the text of the file.
    Console.WriteLine(trs.ReadToEnd());

    //Or Can Reading a line of the text file.
    //Console.WriteLine(trs.ReadLine());

    //Close the file.
    trs.Close();

    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();


    Hope this helped you.
     
    largn81, Jan 26, 2008 IP
  2. Bakie

    Bakie Well-Known Member

    Messages:
    168
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    103
    #2
    Bakie, Jan 27, 2008 IP