Writing Text to a Physical File Using StreamWriter in C#
By FoxLearn 2/7/2025 3:07:15 AM 78
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#
Categories
Popular Posts
Stisla Admin Dashboard Template
11/18/2024
Admin Tailwind CSS Admin Dashboard Template
11/18/2024
Portal HTML Bootstrap
11/14/2024