C# .NET: CsvHelper: Read\Write List<string>

5/5/2020 3:07:56 PM

Write a List to a CSV file.

//list to output
var urls = new List<string>()
{
	"https://www.codelocker.net/",
	"https://www.convertimages.net/"
};


using (var writer = new System.IO.StreamWriter(@"C:\Users\Me\Documents\urls.csv"))
{
	using (var csv = new CsvHelper.CsvWriter(writer, System.Globalization.CultureInfo.InvariantCulture))
	{		
		foreach (var url in urls)
		{
			csv.WriteField(url);
			csv.NextRecord();
		}

		writer.Flush();                                        
	}
}

Read a single column CSV file into a List

//list to input to
var urls = new List<string>();

using (var reader = new System.IO.StreamReader(@"C:\Users\Me\Documents\urls.csv"))
{
	using (var csv = new CsvHelper.CsvReader(reader, System.Globalization.CultureInfo.InvariantCulture))
	{
		//uncomment if a header row exists
		//csv.Read();
        //csv.ReadHeader();
				
		while (csv.Read())
		{
			var url = csv.GetField(0);

			urls.Add(url);
		}
	}
}