Search code examples
c#csvvisual-studio-2012headerconsole.writeline

Adding headers into CSV output file using StreamWriter


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

Solution

  • I propose you following modification

    using (StreamWriter file = new StreamWriter(fs))                    
    {
        file.WriteLine("ProjectID, ProjectTitle,PublishStatus,Length");
        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); 
    
    }//end of for