C# Write File

Open and write a file using streams:

using System.IO;
StreamReader sr = new StreamReader("test.txt");
StreamWriter sw = new StreamWriter("copy.txt");
string strLine = sr.ReadLine();
while (!sr.EndOfStream)
{
...
sw.WriteLine(strLine);
strLine = sr.ReadLine();
}
sr.Close();
sw.Close();

Appen or overrite the file and encoding.
using System.IO;
using System.Text;
StreamWriter sw = new StreamWriter("copy.txt", true); //append
StreamWriter sw = new StreamWriter("copy.txt", false); //overwrite
StreamWriter sw = new StreamWriter("copy.txt", false, Encoding.UTF8); //overwrite and UTF8 format

If the file is relatively small, it can be read as one string at one time.
using System.IO;
string str = File.ReadAllText("test.txt");
File.WriteAllText("copy.txt",str);

To read and write a file line by line.
using System.IO;
string[] arrlines = File.ReadAllLines("Text.txt");
foreach (string thisline in arrlines)
{
File.WriteAllLines("copy.txt",arrlines);
}
//----------------------------------------
string[] arrstr = {"Monday","Tuesday","Wednesday"};
File.WriteAllLines("copy.txt",arrstr);


endmemo.com © 2024  | Terms of Use | Privacy | Home