Create a Text File and write / read it in C#


In  this article we will see how to create a Text file and write to it, then read its content using StreamWriter and StreamReader classes provided in System.IO namespace. The following example create Text File named "test" and write the sentence "C# Programming Language" in it then read its content and copy it in a TextBox.



First, Remember to add the "using System.IO;" directive as this is the namespace which the StreamReader class is in. And declare this string:
string textfilepath = @"D:\\test.txt";


This is the code to  create the Text File and write to it:
 
private void CreateTextFileButton_Click(object sender, EventArgs e)
{
    using (StreamWriter write = new StreamWriter(textfilepath))
    {
        write.WriteLine("C# Programming Language");
    } 
}

And this is the code to read the Text File content:

private void ReadTextFileButton_Click(object sender, EventArgs e)
{
    using (StreamReader read = new StreamReader(textfilepath))
    {
        while (true)
        {
            string line = read.ReadLine();
            if (line == null)
            {
                break;
            }
            textBox1.Text = line;
        }
   }
}

Create a Text File and write / read it in C# Create a Text File and write / read it in C# Reviewed by Bloggeur DZ on 03:14 Rating: 5

Aucun commentaire:

Fourni par Blogger.