Easiest way to read from and write to files
In addition to File.ReadAllText
, File.ReadAllLines
, and File.WriteAllText
(and similar helpers from File
class) shown in another answer you can use StreamWriter
/StreamReader
classes.
Writing a text file:
using(StreamWriter writetext = new StreamWriter("write.txt"))
{
writetext.WriteLine("writing in text file");
}
Reading a text file:
using(StreamReader readtext = new StreamReader("readme.txt"))
{
string readText = readtext.ReadLine();
}
Notes:
- You can use
readtext.Dispose()
instead ofusing
, but it will not close file/reader/writer in case of exceptions - Be aware that relative path is relative to current working directory. You may want to use/construct absolute path.
- Missing
using
/Close
is very common reason of "why data is not written to file".
FileStream fs = new FileStream(txtSourcePath.Text,FileMode.Open, FileAccess.Read);
using(StreamReader sr = new StreamReader(fs))
{
using (StreamWriter sw = new StreamWriter(Destination))
{
sw.Writeline("Your text");
}
}
Use File.ReadAllText and File.WriteAllText.
MSDN example excerpt:
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
...
// Open the file to read from.
string readText = File.ReadAllText(path);