Writing Text to a Physical File Using StreamWriter in C#
By FoxLearn 2/7/2025 3:07:15 AM 108
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.
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
How to secure ASP.NET Core with NWebSec
11/07/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024