How can I read, write, and modify the contents of a notepad (.txt) file in Winform and WPF C#?
Asked
Active
Viewed 7,824 times
-5
-
check out System.IO.File http://msdn.microsoft.com/en-us/library/system.io.file.aspx – Jonesopolis Jul 10 '13 at 15:39
-
https://www.google.com/search?q=c%23+read+write+file – ken2k Jul 10 '13 at 15:39
-
What's the text encoding? – Sebastian Negraszus Jul 10 '13 at 15:43
3 Answers
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: