Using String.Format() Method in .NET 5.0 in C#

Advertisements

I am a new user to C# and I am having difficulty with one last thing to finish this script I am working on. I am in .NET 5.0. I am working on writing some results out to a csv file but when I use the string.Format() method, I am only getting the first value returned to the console, or the csv for that matter.

string newLine = string.Format("Value1", "Value2");
Console.WriteLine(newLine);

I am inside of a loop, and all lines are being returned, buy only Value1 is being returned on each line, not Value2. Any help would be appreciated.

>Solution :

I don’t think you understand how string.Format() works at all. The first argument is a base string, which should include placeholders (ie: {0}, {1}, etc). Additional arguments then fill in the placeholders in order.

So if you want CSV data, it sounds like you want something more like this:

string newLine = string.Format("{0},{1}", "Value1", "Value2");
Console.WriteLine(newLine);

Or from an array like this:

string[] row = {"Value1", "Value2"};
string newLine = string.Format("{0},{1}", row);
Console.WriteLine(newLine);

Or maybe you’d prefer string.Join(), which can handle an arbitrary number of values without needing placeholders:

string[] row = {"Value1", "Value2"};
string newLine = string.Join(",", row);
Console.WriteLine(newLine);

But really, even simple CSV files have a surprising number of edge cases and gotchas, and you’ll likely be MUCH better off to get a CSV library from NuGet.

Leave a ReplyCancel reply