khany
khany

Reputation: 1187

c# streamwriter add line on file creation

I am successfully writing data to csv files (yay!) in a Console App. Streamwriter is excellent for me up to now.

using (StreamWriter writer = new StreamWriter(file, true))
{
    writer.WriteLine(strToSave);
}

This codes appends to an existing file or, if it doesn't exist, creates a new file first then writes.

What I want it to do is, if the file doesn't exist, create the file, write a header line for the csv columns, then write the data as normal. How can I do that?

Thanks.

Upvotes: 0

Views: 3589

Answers (2)

Viacheslav Smityukh
Viacheslav Smityukh

Reputation: 5843

You can check the length property of a stream

using(var stream = new FileStream("file.name", FileMode.OpenOrCreate, FileAccess.ReadWrite))
using (var writer = new StreamWriter(stream))
{
    if (stream.Length == 0)
    {
        // Write header here
    }
}

Upvotes: 0

Nikola Davidovic
Nikola Davidovic

Reputation: 8666

You could first check weather the file exists using File.Exists() method. If the file already exists, you don't need to write the header, and if the exists value is false, write header (supposing that the header of the .csv is in the variable header) and then write the text you want.

        bool exists = File.Exists(file);
        using (StreamWriter writer = new StreamWriter(file, true))
        {
            if(!exists)
                writer.WriteLine(header);
            writer.WriteLine(strToSave);
        }

Upvotes: 6

Related Questions