How To Implement .NET Core CSV Writer

Let's discuss how to implement Generic CSV Writer which may take an input from any list and return a CSV string or write to a certain file, if specified. Although, this is a generic C# implementation and can be used in any .NET Framework supporting generics. Yet, we are going to discuss this with .NET Core. We are going to use .NET Core Console Application which is in continuation to Welcome to .NET Core Console Application.

Add new Class in DotNetCore.ConsoleApplication

We are going to add a new class CsvWriter in DotNetCore.ConsoleApplication.

  • Open existing solution in Visual Studio 2015.
  • Now, add a new class CsvWriter.cs.

    • Open Add New Item Screen through DotNetCore.ConsoleApplication Context Menu of Common folder >> Add >> Class >> Installed >> .NET Core >> Class.
    • Name it CsvWriter.cs.
    • Click OK button.

  • Add CsvWriter implementation.

    • Write<T> (IList<T> list, bool includeHeader = true).
    • Creates and returns the generated CSV. 
    • Write<T> (IList<T> list, string fileName, bool includeHeader = true)
      Creates and returns the generated CSV and saves the generated CSV to the specified path.
    • CreateCsvHeaderLine
    • Creates CSV header line, if includeHeader is set true.
    • CreateCsvLine<T>(T item, PropertyInfo[] properties).
      Creates a CSV line for the given type of the object.
    • CreateCsvLine(IList<string> list).
      Creates a CSV line for the given list of the string by joining them, demarcated by comma.

    • CreateCsvItem
      Adds the provided value item to the processed list, used to create CSV line.

    • CreateCsvStringListItem
      Adds the provided string list as a single item to the processed list, which is used to create CSV line.

    • CreateCsvStringArrayItem
      Adds the provided string array as a single item to the processed list, which is used to create CSV line.

    • CreateCsvStringItem
      Adds the provided string value item to the processed list, used to create CSV line.

    • ProcessStringEscapeSequence
      Processes the provided data to handle double quotes and comma value. If we do not apply escape sequences, they can corrupt the data.

    • WriteFile
      Writes the generated CSV data to the file.

ConsoleApplication

  1. public class CsvWriter {  
  2.     privateconst string DELIMITER = ",";  
  3.   
  4.     public string Write < T > (IList < T > list, bool includeHeader = true) {  
  5.         StringBuildersb = new StringBuilder();  
  6.   
  7.         Type type = typeof(T);  
  8.   
  9.         PropertyInfo[] properties = type.GetProperties();  
  10.   
  11.         if (includeHeader) {  
  12.             sb.AppendLine(this.CreateCsvHeaderLine(properties));  
  13.         }  
  14.   
  15.         foreach(var item in list) {  
  16.             sb.AppendLine(this.CreateCsvLine(item, properties));  
  17.         }  
  18.   
  19.         returnsb.ToString();  
  20.     }  
  21.   
  22.     public string Write < T > (IList < T > list, string fileName, bool includeHeader = true) {  
  23.         string csv = this.Write(list, includeHeader);  
  24.   
  25.         this.WriteFile(fileName, csv);  
  26.   
  27.         return csv;  
  28.     }  
  29.   
  30.     private string CreateCsvHeaderLine(PropertyInfo[] properties) {  
  31.         List < string > propertyValues = new List < string > ();  
  32.   
  33.         foreach(var prop in properties) {  
  34.             stringstringformatString = string.Empty;  
  35.             string value = prop.Name;  
  36.   
  37.             var attribute = prop.GetCustomAttribute(typeof(DisplayAttribute));  
  38.             if (attribute != null) {  
  39.                 value = (attribute as DisplayAttribute).Name;  
  40.             }  
  41.   
  42.             this.CreateCsvStringItem(propertyValues, value);  
  43.         }  
  44.   
  45.         returnthis.CreateCsvLine(propertyValues);  
  46.     }  
  47.   
  48.     private string CreateCsvLine < T > (T item, PropertyInfo[] properties) {  
  49.         List < string > propertyValues = new List < string > ();  
  50.   
  51.         foreach(var prop in properties) {  
  52.             stringstringformatString = string.Empty;  
  53.             object value = prop.GetValue(item, null);  
  54.   
  55.             if (prop.PropertyType == typeof(string)) {  
  56.                 this.CreateCsvStringItem(propertyValues, value);  
  57.             } else if (prop.PropertyType == typeof(string[])) {  
  58.                 this.CreateCsvStringArrayItem(propertyValues, value);  
  59.             } else if (prop.PropertyType == typeof(List < string > )) {  
  60.                 this.CreateCsvStringListItem(propertyValues, value);  
  61.             } else {  
  62.                 this.CreateCsvItem(propertyValues, value);  
  63.             }  
  64.         }  
  65.   
  66.         returnthis.CreateCsvLine(propertyValues);  
  67.     }  
  68.   
  69.     private string CreateCsvLine(IList < string > list) {  
  70.         returnstring.Join(CsvWriter.DELIMITER, list);  
  71.     }  
  72.   
  73.     private void CreateCsvItem(List < string > propertyValues, object value) {  
  74.         if (value != null) {  
  75.             propertyValues.Add(value.ToString());  
  76.         } else {  
  77.             propertyValues.Add(string.Empty);  
  78.         }  
  79.     }  
  80.   
  81.     private void CreateCsvStringListItem(List < string > propertyValues, object value) {  
  82.         string formatString = "\"{0}\"";  
  83.         if (value != null) {  
  84.             value = this.CreateCsvLine((List < string > ) value);  
  85.             propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value)));  
  86.         } else {  
  87.             propertyValues.Add(string.Empty);  
  88.         }  
  89.     }  
  90.   
  91.     private void CreateCsvStringArrayItem(List < string > propertyValues, object value) {  
  92.         string formatString = "\"{0}\"";  
  93.         if (value != null) {  
  94.             value = this.CreateCsvLine(((string[]) value).ToList());  
  95.             propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value)));  
  96.         } else {  
  97.             propertyValues.Add(string.Empty);  
  98.         }  
  99.     }  
  100.   
  101.     private void CreateCsvStringItem(List < string > propertyValues, object value) {  
  102.         string formatString = "\"{0}\"";  
  103.         if (value != null) {  
  104.             propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value)));  
  105.         } else {  
  106.             propertyValues.Add(string.Empty);  
  107.         }  
  108.     }  
  109.   
  110.     private string ProcessStringEscapeSequence(object value) {  
  111.         returnvalue.ToString().Replace("\"", "\"\"");  
  112.     }  
  113.   
  114.     public bool WriteFile(string fileName, string csv) {  
  115.         boolfileCreated = false;  
  116.   
  117.         if (!string.IsNullOrWhiteSpace(fileName)) {  
  118.             File.WriteAllText(fileName, csv);  
  119.   
  120.             fileCreated = true;  
  121.         }  
  122.   
  123.         returnfileCreated;  
  124.     }  
  125. }  
Add Test Model Class in DotNetCore.ConsoleApplication

We are going to add a new class TestVM in DotNetCore.ConsoleApplication.
  • Open the existing Solution in Visual Studio 2015.
  • Now, add a new class TestVM.cs.

    • Open Add New Item Screen through DotNetCore.ConsoleApplication Context Menu of Common folder >> Add >> Class >> Installed >> .NET Core >> Class.
    • Name it TestVM.cs.
    • Click OK button.

  • Add TestVM implementation.
  • Update Program.cs to initialize List<TestVM> with the dummy data and call CsvWriter.

public class CsvWriter {     privateconst string DELIMITER = ",";      public string Write < T  /> (IList < T > list, bool includeHeader = true) {         StringBuildersb = new StringBuilder();          Type type = typeof(T);          PropertyInfo[] properties = type.GetProperties();          if (includeHeader) {             sb.AppendLine(this.CreateCsvHeaderLine(properties));         }          foreach(var item in list) {             sb.AppendLine(this.CreateCsvLine(item, properties));         }          returnsb.ToString();     }      public string Write < T > (IList < T > list, string fileName, bool includeHeader = true) {         string csv = this.Write(list, includeHeader);          this.WriteFile(fileName, csv);          return csv;     }      private string CreateCsvHeaderLine(PropertyInfo[] properties) {         List < string > propertyValues = new List < string > ();          foreach(var prop in properties) {             stringformatString = string.Empty;             string value = prop.Name;              var attribute = prop.GetCustomAttribute(typeof(DisplayAttribute));             if (attribute != null) {                 value = (attribute as DisplayAttribute).Name;             }              this.CreateCsvStringItem(propertyValues, value);         }          returnthis.CreateCsvLine(propertyValues);     }      private string CreateCsvLine < T > (T item, PropertyInfo[] properties) {         List < string > propertyValues = new List < string > ();          foreach(var prop in properties) {             stringformatString = string.Empty;             object value = prop.GetValue(item, null);              if (prop.PropertyType == typeof(string)) {                 this.CreateCsvStringItem(propertyValues, value);             } else if (prop.PropertyType == typeof(string[])) {                 this.CreateCsvStringArrayItem(propertyValues, value);             } else if (prop.PropertyType == typeof(List < string > )) {                 this.CreateCsvStringListItem(propertyValues, value);             } else {                 this.CreateCsvItem(propertyValues, value);             }         }          returnthis.CreateCsvLine(propertyValues);     }      private string CreateCsvLine(IList < string > list) {         returnstring.Join(CsvWriter.DELIMITER, list);     }      private void CreateCsvItem(List < string > propertyValues, object value) {         if (value != null) {             propertyValues.Add(value.ToString());         } else {             propertyValues.Add(string.Empty);         }     }      private void CreateCsvStringListItem(List < string > propertyValues, object value) {         string formatString = "\"{0}\"";         if (value != null) {             value = this.CreateCsvLine((List < string > ) value);             propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value)));         } else {             propertyValues.Add(string.Empty);         }     }      private void CreateCsvStringArrayItem(List < string > propertyValues, object value) {         string formatString = "\"{0}\"";         if (value != null) {             value = this.CreateCsvLine(((string[]) value).ToList());             propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value)));         } else {             propertyValues.Add(string.Empty);         }     }      private void CreateCsvStringItem(List < string > propertyValues, object value) {         string formatString = "\"{0}\"";         if (value != null) {             propertyValues.Add(string.Format(formatString, this.ProcessStringEscapeSequence(value)));         } else {             propertyValues.Add(string.Empty);         }     }      private string ProcessStringEscapeSequence(object value) {         returnvalue.ToString().Replace("\"", "\"\"");     }      public bool WriteFile(string fileName, string csv) {         boolfileCreated = false;          if (!string.IsNullOrWhiteSpace(fileName)) {             File.WriteAllText(fileName, csv);              fileCreated = true;         }          returnfileCreated;     } }

  1. public class TestVM {  
  2.     [Display(Name = "Test Id")]  
  3.     publicintTestId {  
  4.         get;  
  5.         set;  
  6.     }  
  7.     [Display(Name = "Name")]  
  8.     public string TestName {  
  9.         get;  
  10.         set;  
  11.     }  
  12. }  
  13.   
  14. public class Program {  
  15.     public static void Main(string[] args) {  
  16.         Console.WriteLine("Welcome to .NET Core Console Application");  
  17.         List < TestVM > tests = new List < TestVM > {  
  18.             newTestVM {  
  19.                 TestId = 1TestName = "Bill Gates"  
  20.             },  
  21.             newTestVM {  
  22.                 TestId = 2TestName = "Warren Buffett"  
  23.             },  
  24.             newTestVM {  
  25.                 TestId = 3TestName = "Amancio Ortega"  
  26.             },  
  27.             newTestVM {  
  28.                 TestId = 4TestName = "Carlos Slim Helu"  
  29.             }  
  30.         };  
  31.         stringstringfileName = string.Format("{0}\\test.csv", System.AppContext.BaseDirectory);  
  32.         CsvWritercsvWriter = new CsvWriter();  
  33.         csvWriter.Write(tests, fileName, true);  
  34.         Console.WriteLine("{0} has been created.", fileName);  
  35.         Console.ReadKey();  
  36.     }  
  37. }  
Run Application in Debug Mode
  • Press F5 or Debug Menu >> Start Debugging or Start Console Application button on the toolbar to start the Application in the debugging mode. It will start an Application Console in the debug mode.
  • It will generate test.csv at given path. Therefore at C:\ASP.NET Core\CSV Writer\DotNetCore\ConsoleApplication.NetCore\bin\Debug\netcoreapp1.0.

public class TestVM {     [Display(Name = "Test Id")]     publicintTestId {         get;         set;     }     [Display(Name = "Name")]     public string TestName {         get;         set;     } }  public class Program {     public static void Main(string[] args) {         Console.WriteLine("Welcome to .NET Core Console Application");         List < TestVM  /> tests = new List < TestVM > {             newTestVM {                 TestId = 1, TestName = "Bill Gates"             },             newTestVM {                 TestId = 2, TestName = "Warren Buffett"             },             newTestVM {                 TestId = 3, TestName = "Amancio Ortega"             },             newTestVM {                 TestId = 4, TestName = "Carlos Slim Helu"             }         };         stringfileName = string.Format("{0}\\test.csv", System.AppContext.BaseDirectory);         CsvWritercsvWriter = new CsvWriter();         csvWriter.Write(tests, fileName, true);         Console.WriteLine("{0} has been created.", fileName);         Console.ReadKey();     } }

Sample Source Code

I have placed the sample code for this session in ".NET Core CSV Writer_Code.zip" in CodePlex repository.


Similar Articles