---
title: "How to write file using StreamWriter in C#?"  
description: "How to write file using StreamWriter in C#?"  
author: "Sandra Emily"  
published: 2024-06-13  
updated: 2024-06-13  
canonical: https://www.mindstick.com/forum/160741/how-to-write-file-using-streamwriter-in-c-sharp  
category: "c#"  
tags: ["c#", "file", "programming language", "file handling"]  
reading_time: 2 minutes  

---

# How to write file using StreamWriter in C#?

How to write [file using StreamWriter](https://www.mindstick.com/forum/161596/how-can-you-append-lines-to-a-file-using-streamwriter-without-overwriting-existing-content) in C#?

## Replies

### Reply by Ashutosh Patel

#### C# StreamWriter for writing file

In c#, you can write the text to a [file](https://www.mindstick.com/articles/59/encrypting-and-decrypting-files-using-c-sharp) using the [StreamWriter](https://www.mindstick.com/interview/34097/how-can-you-write-to-a-file-using-streamwriter-with-async-await) class.

## Example-

Here is a simple example to demonstrates the StreamWriter in c# for writing the text to the file,

```cs
using System;
using System.IO;
class Program
{
   static void Main()
   {
       // Specify the file path
       string filePath = "Sample.txt";
       // Create a StreamWriter instance to write in the file
       using (StreamWriter writer = new StreamWriter(filePath))
       {
           // Write text to the file
           writer.WriteLine("Hello, world!");
           writer.WriteLine("This is a test.");
           writer.WriteLine("Writing sample text to a file using C# StreamWriter class.");
       }
       Console.WriteLine("Text has been written to the file.");
       Console.ReadLine();
   }
}
```

## In the above example-

- We specify the file `path`where we want to write the text (`sample.txt`).
- We create a `StreamWriter`instance named writer and pass the file **path** to its **constructor**.
- We use the `WriteLine`method of the `StreamWriter`instance to write text to the file.
- The transaction ensures that the `StreamWriter`is properly disposed of after use, which locks the file and frees any associated objects.

## Output-

![How to write file using StreamWriter in C#?](https://www.mindstick.com/mindstickforums/2596e3b5-2669-46b2-b1bf-25a021506334/images/c49de0a3-0bc3-4a42-9797-fb85375c28c1.png)

**Also, Read:** [Difference between Array and ArrayList](https://www.mindstick.com/forum/160742/difference-between-array-and-arraylist)


---

Original Source: https://www.mindstick.com/forum/160741/how-to-write-file-using-streamwriter-in-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
