In c#, you can write the text to a file using the StreamWriter class.
Example-
Here is a simple example to demonstrates the StreamWriter in c# for writing the text to the file,
using System;
using System.IO;
class Program
{
static void Main()
{
// Specify the file path
string filePath = "Sample.txt";
// Create a StreamWriter instance to write in the file
using (StreamWriter writer = new StreamWriter(filePath))
{
// Write text to the file
writer.WriteLine("Hello, world!");
writer.WriteLine("This is a test.");
writer.WriteLine("Writing sample text to a file using C# StreamWriter class.");
}
Console.WriteLine("Text has been written to the file.");
Console.ReadLine();
}
}
In the above example-
We specify the file path where we want to write the text (sample.txt).
We create a StreamWriter instance named writer and pass the file
path to its constructor.
We use the WriteLine method of the StreamWriter instance to write text to the file.
The transaction ensures that the StreamWriter is properly disposed of after use, which locks the file and frees any associated objects.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
C# StreamWriter for writing file
In c#, you can write the text to a file using the StreamWriter class.
Example-
Here is a simple example to demonstrates the StreamWriter in c# for writing the text to the file,
In the above example-
pathwhere we want to write the text (sample.txt).StreamWriterinstance named writer and pass the file path to its constructor.WriteLinemethod of theStreamWriterinstance to write text to the file.StreamWriteris properly disposed of after use, which locks the file and frees any associated objects.Output-
Also, Read: Difference between Array and ArrayList