Theomax
Theomax

Reputation: 6792

How to add header line to CSV without loading whole file?

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.

Upvotes: 3

Views: 751

Answers (2)

Liu
Liu

Reputation: 982

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);
}

Upvotes: 2

Kevin Raffay
Kevin Raffay

Reputation: 842

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

Upvotes: 1

Related Questions