3

I have a console application and I would like to add a header row to a CSV file without loading the data into the application. What code do I need to do this but also to check only the first line to see if the headers already exist and if they do then not add the header row? I have tried a few ways of doing this but cannot find a way of coding this without loading the whole file to check if it exists and then add the header row.

2 Answers 2

2

You can use StreamReader and StreamWriter to minimize your memory usage.

My suggestion is to read csv file line by line and write it to temp file if you need to add header. Memorywise, it's efficient.

private void AddHeader(string filename)
{
    string tempFilename = "temp.csv";
    bool toCopy = false;

    using (var sw = new StreamWriter(tempFilename, false))
    {
        //check if header exists
        using(var sr = new StreamReader(filename))
        {
            var line = sr.ReadLine(); // first line
            if(line != null && line != "Your Header") // check header exists
            {
                toCopy = true; // need copy temp file to your original csv

                // write your header into the temp file
                sw.WriteLine("Your Header");

                while(line != null)
                {
                    sw.WriteLine(line);
                    line = sr.ReadLine();
                }
            }
        }
    }

    if(toCopy)
        File.Copy(tempFilename, filename, true);
    File.Delete(tempFilename);
}
Sign up to request clarification or add additional context in comments.

9 Comments

Thank you for your code snippet. But how can I add the headers to the CSV file at the top without overwriting the first row in the file?
this solution doesn't overwrite the first row
It adds the row but it adds the headers in the same cell, not in separate cells even though I have separated the headers by commas in the following line: sw.WriteLine("header 1, header 2, header 3") but this is stored in the CSV file as one column and not separate columns. How do I make it store the headers as separate columns?
It sounds like you opened the file in excel. Open it in notepad and lets see what's the separator used in your csv
When you mentioned "cell", you are not looking at the original csv file but formatted by excel. Check my previous comment and see what's the separator using in your csv. Csv doesn't necessarily use comma as separator.
|
1

You can read one line at a time this way, and only add the header if does not exist:

// Read in lines from file.
foreach (string line in File.ReadLines("c:\\file.txt"))
{
    Console.WriteLine("-- {0}", line);
}

https://www.dotnetperls.com/file-readlines

2 Comments

Thank you for your suggestion. But how would I add the headers to the CSV file at the top without overwriting the first row in the file?
In that case, you will have to read the whole file and create a new string builder, starting with your new row. Then save the string builder to the file, but the correct answer will work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.