File class in System.IO Namespace also contains methods to write contents to text tile. WriteAllText() method to write string to text file. WriteAllLines() method is used to write line by line into text file. And WriteLine() method writes or appends text to the text file with existing contents.
How to write to a text file?
TO write to a text file in file system .net has provided below methods in File class of System.IO namespace:
1.WriteAllText.
2.WriteAllLines.
3.WriteLine.
How to write to a text file?
TO write to a text file in file system .net has provided below methods in File class of System.IO namespace:
1.WriteAllText.
2.WriteAllLines.
3.WriteLine.
1.WriteAllText.
WriteAllText method in File class writes one string to the text fileSample code that shows how to write into to text file[C#]
class WriteFileAllText
{
static void Main()
{
// Example to Write one string into text file.
string textToWrite = "To write one string into a text file use
WriteAllText method, " ;
System.IO.File.WriteAllText(@"C:\\TextFileFolder\NewTextFile.txt", textToWrite);
}
}
2.WriteAllLines.
WriteAllLines method in File class writes contents to a text file line by line.Sample code that show how to write into a text file line by line[C#]
class WriteFileLines
{
static void Main()
{
// Example to Write the contents line by line into text file.
string[] lines = {"Line One", "Line Two", "Line Three"};
System.IO.File.WriteAllLines(@"C:\TextFileFolder\WriteLines.txt", lines);}
}
3.WriteLine.
WriteLine method in File class writes or appends line to a text file that already have some data.Sample code that show how to append text line into a text file.[C#]
It uses StreamWriter class of System.IO namespace to append line in existing text fileclass WriteFileLine
{
static void Main()
{
// Append text line to existing file
System.IO.StreamWriter file = new System.IO.StreamWriter ("C:\TextFileFolder\WriteLines.txt", true)
{
file.WriteLine("Line Four");
}
}