Writing Text to a Physical File Using StreamWriter in C#
By Tan Lee Published on Feb 07, 2025 143
To write text to a physical file using StreamWriter in C#, you can follow these steps.
Steps to Use StreamWriter:
Create a
StreamWriter
instance: You need to specify the file path where the text will be written. If the file does not exist,StreamWriter
will create it.Write text: Use the
Write
orWriteLine
methods ofStreamWriter
to write the desired content.Close the file: This ensures the content is flushed to the file and the file handle is released.
For example:
// Create a FileInfo object for the specified path FileInfo fileInfo = new FileInfo(@"C:\Temp\SampleFile.txt"); // Open the file for reading and writing FileStream fileStream = fileInfo.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read); // Create a StreamWriter to write text to the FileStream StreamWriter streamWriter = new StreamWriter(fileStream); streamWriter.WriteLine("This is a new line written using StreamWriter."); streamWriter.WriteLine("StreamWriter can be used to write multiple lines."); // Close the StreamWriter to release the file streamWriter.Close();
In this example:
- FileInfo: This object is created for the specified file path. In this case, the file
"SampleFile.txt"
is in theC:\Temp
directory. - FileStream: The file is opened with the
FileMode.OpenOrCreate
option, which means the file will be opened if it exists, or created if it doesn't. It also specifies the file access asWrite
and allows shared read access. - StreamWriter: This is used to write text to the file via the
FileStream
. You can write multiple lines using theWriteLine
method. - Closing StreamWriter: Always close the
StreamWriter
after writing to ensure data is properly written to the file and the file handle is released.
Categories
Popular Posts
Portal HTML Bootstrap
Nov 13, 2024
Freedash bootstrap lite
Nov 13, 2024
Implementing Caching in ASP.NET Core
Dec 14, 2024
11 Things You Didn't Know About Cloudflare
Dec 19, 2024