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);
}
}
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
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).
来源:https://stackoverflow.com/questions/32357209/adding-headers-into-csv-output-file-using-streamwriter