Eric Sjöström Jennerstrand

Litium E-commerce, C#, .NET MAUI, Javascript, React, Azure, Git. .NET, Node and more!
C Sharp

Write lines to a text file in C#

So do you need to write lines to a text file in C#? Well you’re in luck, here is the really simple way to write text line in C#.
In the example below here. I will show how to create a comma-separated values (CSV) file in C# with just a couple of simple lines. And it’s extremly fast!
Just remember that you have to create the directories yourself. But the StreamWriter will create the file if it do not exists and will overwrite an existing file.

using (var writer = new StreamWriter("C:\\temp\\file\\test.txt"))
{
    writer.WriteLine("ArticleNumber;Price;Stock");

    foreach (var product in listOfProducts)
    {
        writer.WriteLine($"{product.ArticleNumber};{product.Price};{product.Stock}");
    }
}

So the good thing about a using statement. Is that you don’t have to worry about about closing the streamWriter when you are writing lines. Following this, shold be all you have to do write lines to a text file in C#

// filePath is where you want the file to be saved. 
using (var writer = new StreamWriter(filePath))
{
    writer.WriteLine("A line to write");
}
// Adding true will a new line to an existing file.
using (var writer = new StreamWriter(filePath, true))
{
    writer.WriteLine("A line to write");
}

Check out the official documentation on streamwriter here:
https://docs.microsoft.com/en-us/dotnet/api/system.io.streamwriter?view=net-5.0

Create Direcory: https://www.jennerstrand.se/create-directory-in-c/
Create File: https://www.jennerstrand.se/create-file-in-c/

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>