Adding headers into CSV output file using StreamWriter

A arancibia picture A arancibia · Sep 2, 2015 · Viewed 16.4k times · Source

I am trying to add headers into the CSV file and as a headers I would like to have the variables names used in the WriteLine.

Here you have my code:

using (StreamWriter file = new StreamWriter(fs))                    
{
    for (int s = 0; s < pr.Length; ++s)
    {
        string[] UsersIDS = new string[] {""};
        UsersIDS = db.GetUsersList(pr[s].ProjectID);
        file.WriteLine(
             pr[s].ProjectID + '"' + ',' + 
             '"' +  pr[s].ProjectTitle + '"' + ',' + 
             pr[s].PublishStatus + '"' + ',' + 
             UsersIDS.Length); 
    }
}

Answer

Alexei Levenkov picture Alexei Levenkov · Sep 2, 2015

Just regular WriteLine with constant string seem to be what you are after (unless you want to get names of columns via reflection or some other way):

using (StreamWriter file = new StreamWriter(fs))                    
{
    file.WriteLine( "ProjectID,ProjectTitle,PublishStatus,UsersIDS_Length"); 

    for (int index = 0; index < pr.Length; index++)
    {
        var usersIds = db.GetUsersList(pr[s].ProjectID);
        file.WriteLine("{0},\"{1}\",{2},{3}",
           pr[s].ProjectID, pr[s].ProjectTitle,
           pr[s].PublishStatus, usersIds.Length); 
    }
}

(Sound like you also wanted quotes around title... the rest of quotes looked unbalanced).