Bite Size C# – CSV File Creator

Today we will be looking at my CSV Creator class, which is included in my Core.dll library.

It has 1 static method that takes a generic list of objects and a CSV file name. It uses the generic list of objects to construct the CSV file. The properties of the object type contained in the list are used in the creation of the header row of the file. The CSV file name parameter is used to save the created file to disk.

This class in contained in my Core.CSV namespace. Here is the code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Core.CSV
{
    public static class CsvCreator
    {
        public static void CreateCsvFromGenericList<T>(List<T> list, string csvNameWithExt)
        {
            if (list == null || list.Count == 0) return;

            //get type of objects in list
            Type t = list[0].GetType();
            string newLine = Environment.NewLine;

            using (var sw = new StreamWriter(csvNameWithExt))
            {
                //Create an instance of the class
                object o = Activator.CreateInstance(t);
                //Get all properties from class created, this will be used for CSV header row
                PropertyInfo[] props = o.GetType().GetProperties();

                //Create header row based on properties of class
                foreach (
                    PropertyInfo prop in
                        props.Where(prop => prop.Name.ToUpper() != "ENTITYSTATE" 
                        && prop.Name.ToUpper() != "ENTITYKEY"))
                {
                    sw.Write(prop.Name.ToUpper() + ",");
                }
                sw.Write(newLine);

                //create data rows using each object in list
                foreach (T item in list)
                {
                    foreach (string rowData in from pi in props
                                               where !Convert.ToString(item.GetType()
                                                        .GetProperty(pi.Name)
                                                        .GetValue(item, null)).Contains("Unchanged") &&
                                                     !Convert.ToString(item.GetType().GetProperty(pi.Name)
                                                                           .GetValue(item, null))
                                                             .Contains("System.Data.EntityKey")
                                               select Convert.ToString(item.GetType()
                                                                           .GetProperty(pi.Name)
                                                                           .GetValue(item, null))
                                                             .Replace(',', ' ') + ',')
                    {
                        sw.Write(rowData);
                    }
                    sw.Write(newLine);
                }
            }
        }
    }
}

This class is useful when you simply want to create a CSV file from a generic object list quickly.

Bite Size C# – CSV File Creator

3 thoughts on “Bite Size C# – CSV File Creator

  1. JR says:

    Thank you for the comment. This can be done by changing the code snippet:

    foreach (var rowData in from prop in props where !Convert.ToString(item.GetType() .GetProperty(prop.Name) .GetValue(item, null)).Contains(“Unchanged”) && !Convert.ToString(item.GetType() .GetProperty(prop.Name) .GetValue(item, null)).Contains(“System.Data.EntityKey”) select Convert.ToString(item.GetType() .GetProperty(prop.Name) .GetValue(item, null)) .Replace(‘,’, ‘ ‘) + ‘,’)

    To this:

    foreach (var rowData in from prop in props where !Convert.ToString(item.GetType() .GetProperty(prop.Name) .GetValue(item, null)).Contains(“Unchanged”) && !Convert.ToString(item.GetType() .GetProperty(prop.Name) .GetValue(item, null)).Contains(“System.Data.EntityKey”) select Convert.ToString(item.GetType() .GetProperty(prop.Name) .GetValue(item, null)) .Replace(“,”, “\,”).Replace(“‘”, “\'”) + ‘,’)

    Double quotes would already have been escaped when they were read into the C# string.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s