Write a file using StreamWriter in C#:
The StreamWriter
is used to write the characters to a stream. It is available under the namespace System.IO
.
The FileInfo provides properties and instance methods for creating, copying, deleting, moving, and opening files, and helps create FileStream objects.
// Create fileInfo object and specify path
FileInfo fileInfo = new FileInfo(@"E:\Test_File.txt");
The FileStream provides a stream for a file and is used for reading and writing operations.
// Open the file for Reading and Writing
FileStream fileStream = fileInfo.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
Code Snippet:
The below example is used to create the file and append or add the new text to the file.
using System.IO;
namespace StreamWriterSample
{
class Program
{
static void Main(string[] args)
{
// Create fileInfo object and specify path
FileInfo fileInfo = new FileInfo(@"E:\Test_File.txt");
// Open the file for Read and Write
FileStream fileStream = fileInfo.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
// Write string to the FileSream object
StreamWriter streamWriter = new StreamWriter(fileStream);
streamWriter.WriteLine("Sample text inserted to the file");
streamWriter.Close();
}
}
}
You can also visit the below blog to create and delete a file using StreamWriter & StreamReader in C#.
Comments (0)