Close

NuGet package CsvHelper

I came across an interesting NuGet package named CsvHelper. CsvHelper basically let’s you create a Csv file from a typed list. You can choose whether or not to include a header automatically. As an example, let’s say you access AFAS to get a list of users.

private static async Task<List<ASB_Totara_User>> GetAfasUserAsync(Logging logging)
{

string take = 1000;
string path = string.Format(“https://99999.afasonlineconnector.nl/profitrestservices/connectors/ASB_Totara_User?take={0}&Orderbyfieldids=idnumber”, take);

String content;

List<ASB_Totara_User> users = new List<ASB_Totara_User>();

_afasClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“AfasToken”, ConfigurationManager.AppSettings[“AfasToken”]);
using (HttpResponseMessage response = await _afasClient.GetAsync(path))
{
using (Stream responseStream = await response.Content.ReadAsStreamAsync())
{
using (StreamReader reader = new StreamReader(responseStream))
{
// Get untyped content
content = reader.ReadToEnd();
// Convert to typed response
UserResponse userResponse = JsonConvert.DeserializeObject<UserResponse>(content);
if (userResponse != null)
{
users = userResponse.rows;
}

userResponse = null;
}
}
}

return users;

}

Next you can call another routine to create a Csv file:

// Write CSV content
using (var stream = new MemoryStream())
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
using (var csv = new CsvWriter(writer))
{
csv.Configuration.Delimiter = “;”;

csv.WriteRecords(users);

writer.Flush();
stream.Position = 0;

userResult.Data = reader.ReadToEnd();
}

Variable userResult.Data is a generic type of type T.

For help on reading and writing Csv files, see: CsvHelper documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *