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:

  1. 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.

  2. Write text: Use the Write or WriteLine methods of StreamWriter to write the desired content.

  3. 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 the C:\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 as Write and allows shared read access.
  • StreamWriter: This is used to write text to the file via the FileStream. You can write multiple lines using the WriteLine method.
  • Closing StreamWriter: Always close the StreamWriter after writing to ensure data is properly written to the file and the file handle is released.