Amicheals
Amicheals

Reputation: 147

C# take output and put it into CSV file

I have some code that is currently doing the following at the end of the code:

Console.WriteLine(vid.totalCurrentCharges + " : " + vid.assetId + " : " + vid.componentName + " : " + vid.recurringCharge);
Console.readline().

I need to take the output of vid.totalCurrentCharges + " : " + vid.assetId + " : " + vid.componentName + " : " + vid.recurringCharge, and write It to a csv file. Can someone here help with this? Currently all it is doing is writing the output to console.

Upvotes: 1

Views: 120

Answers (1)

Piotr Stapp
Piotr Stapp

Reputation: 19830

Instead of Console.Writeline you need to create StreamWriter. Just like this:

using (StreamWriter writer = new StreamWriter("important.csv"))
{
//probably a loop here
   writer.WriteLine(vid.totalCurrentCharges + " , " + vid.assetId + " , " + vid.componentName + " , " + vid.recurringCharge);
}

Moreover you can use String.Join to concatenate strings instead of "adding" them, so above WriteLine can be converted into:

writer.WriteLine(String.Join(",", vid.totalCurrentCharges, vid.assetId, vid.componentName, vid.recurringCharge));

Upvotes: 2

Related Questions