Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading