-5

How can I read, write, and modify the contents of a notepad (.txt) file in Winform and WPF C#?

Sebastian Negraszus
  • 11,915
  • 7
  • 43
  • 70
user2555148
  • 19
  • 2
  • 5

3 Answers3

1

Easiest is StreamReader and StreamWriter:

    using (var writer = new StreamWriter(@"C:\blah\somefile.txt"))
    {
        writer.WriteLine("Hello!");
    }

    using (var reader = new StreamReader(@"C:\blah\somefile.txt"))
    {
        var line = reader.ReadLine();
    }
Jon G
  • 4,083
  • 22
  • 27
0

You just have to use System.IO.File.

class WriteTextFile
{
    static void Main()
    {

        // These examples assume a "C:\Users\Public\TestFolder" folder on your machine.
        // You can modify the path if necessary.

        // Example #1: Write an array of strings to a file.
        // Create a string array that consists of three lines.
        string[] lines = {"First line", "Second line", "Third line"};
        System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);


        // Example #2: Write one string to a text file.
        string text = "A class is the most powerful data type in C#. Like structures, " +
                       "a class defines the data and behavior of the data type. ";
        System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);

        // Example #3: Write only some strings in an array to a file.
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
        {
            foreach (string line in lines)
            {
                // If the line doesn't contain the word 'Second', write the line to the file.
                if (!line.Contains("Second"))
                {
                    file.WriteLine(line);
                }
            }
        }

        // Example #4: Append new text to an existing file
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
        {
            file.WriteLine("Fourth line");
        }  
    }
}
/* Output (to WriteLines.txt):
    First line
    Second line
    Third line

 Output (to WriteText.txt):
    A class is the most powerful data type in C#. Like structures, a class defines the data and behavior of the data type.

 Output to WriteLines2.txt after Example #3:
    First line
    Third line

 Output to WriteLines2.txt after Example #4:
    First line
    Third line
    Fourth line
 */
Alex
  • 2,927
  • 8
  • 37
  • 56
  • Add credit where it's due: [MSDN - How to: Write to a Text File](http://msdn.microsoft.com/en-us/library/8bh11f1k(v=vs.90).aspx) – tnw Jul 10 '13 at 15:58
0

This is a very basic topic and there's already a lot of information out there only a simple search away. As an example here is a SO question that should get you started:

How to both read and write a file in C#

Community
  • 1
  • 1
Matt
  • 13,948
  • 6
  • 44
  • 68