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.
Add a comment
|
2 Answers
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);
}
9 Comments
Theomax
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?
Liu
this solution doesn't overwrite the first row
Theomax
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?
Liu
It sounds like you opened the file in excel. Open it in notepad and lets see what's the separator used in your csv
Liu
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.
|
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);
}
2 Comments
Theomax
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?
Kevin Raffay
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.