C#.NET Import/Export CSV Library

This article is about the creation of a simple C#.NET base class library for importing/exporting the CSV data using Datatable as a primary data structure.

Importing and exporting are some of the basic operations used in any sort of development. So, for this purpose, I have created a very simple C#.NET library for importing/exporting the CSV data using Datatable as a primary data structure. You can use this library into your C#.NET project that supports Datatable data structure. This library imports CSV files with or without header and with any number of columns into C#.NET Datatable structure. The import function will automatically detect the number of columns of the CSV file. The export method will export your data from C#.NET Datatable data structure to .csv format file.
 
Today, I shall be demonstrating the creation of a simple C#.NET base class library for importing/exporting CSV data using Datatable as a primary data structure.
 
C#.Net Import/Export CSV Library
 
Prerequisites
 
Following are some prerequisites before you proceed any further in this tutorial.
  1. Knowledge of C# Programming.
You can install this library via NuGet packages; or
you can download pre-compiled DLL library; or
you can download the code and compile the DLL library file yourself; or
you can follow the step by step discussion below.
 
The sample code is being developed in Microsoft Visual Studio 2017 Professional.
 
 
Let's begin now.
 
Step 1
 
Create a new Windows Desktop app -> Class Library (.NET Framework) project and name it "CSVLibraryAK".
 
Step 2
 
Create the "CSVLibraryAK.cs" file and replace the following code in it.
  1. //-----------------------------------------------------------------------  
  2. // <copyright file="CSVLibraryAK.cs" company="None">  
  3. //     Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.  
  4. // </copyright>  
  5. // <author>Asma Khalid</author>  
  6. //-----------------------------------------------------------------------  
  7.   
  8. namespace CSVLibraryAK  
  9. {  
  10.     using System;  
  11.     using System.Collections.Generic;  
  12.     using System.Data;  
  13.     using System.IO;  
  14.     using System.Linq;  
  15.     using System.Text;  
  16.     using System.Web;  
  17.     using Resources.Constants;  
  18.   
  19.     /// <summary>  
  20.     /// CSV library class.  
  21.     /// </summary>  
  22.     public class CSVLibraryAK  
  23.     {  
  24.         #region Import Data method.  
  25.   
  26.         /// <summary>  
  27.         /// Import Data method.  
  28.         /// </summary>  
  29.         /// <param name="srcFilePath">Source file path parameter</param>  
  30.         /// <param name="hasHeader">Has header parameter</param>  
  31.         /// <returns>Returns CSV data as data table</returns>  
  32.         public static DataTable Import(string srcFilePath, bool hasHeader)  
  33.         {  
  34.             // Initilization  
  35.             DataTable datatable = new DataTable();  
  36.             StreamReader sr = null;  
  37.   
  38.             try  
  39.             {  
  40.                 // Creating data table without header.  
  41.                 using (sr = new StreamReader(new FileStream(srcFilePath, FileMode.Open, FileAccess.Read)))  
  42.                 {  
  43.                     // Initialization.  
  44.                     string line = string.Empty;  
  45.                     string[] headers = sr.ReadLine().Split(',');  
  46.                     DataRow dr = datatable.NewRow();  
  47.   
  48.                     // Preparing header.  
  49.                     for (int i = 0; i < headers.Length; i++)  
  50.                     {  
  51.                         // Verification.  
  52.                         if (hasHeader)  
  53.                         {  
  54.                             // Setting.  
  55.                             datatable.Columns.Add(headers[i]);  
  56.                         }  
  57.                         else  
  58.                         {  
  59.                             // Setting.  
  60.                             datatable.Columns.Add(Strings.COL_HEADER_1 + i);  
  61.                             dr[i] = headers[i];  
  62.                         }  
  63.                     }  
  64.   
  65.                     // Verification.  
  66.                     if (!hasHeader)  
  67.                     {  
  68.                         // Adding.  
  69.                         datatable.Rows.Add(dr);  
  70.                     }  
  71.   
  72.                     // Adding data.  
  73.                     while ((line = sr.ReadLine()) != null)  
  74.                     {  
  75.                         // Initialization.  
  76.                         string[] rows = line.Split(',');  
  77.                         dr = datatable.NewRow();  
  78.   
  79.                         // Verification  
  80.                         if (string.IsNullOrEmpty(line))  
  81.                         {  
  82.                             // Info.  
  83.                             continue;  
  84.                         }  
  85.   
  86.                         // Adding row.  
  87.                         for (int i = 0; i < headers.Length; i++)  
  88.                         {  
  89.                             // Setting.  
  90.                             dr[i] = rows[i];  
  91.                         }  
  92.   
  93.                         // Adding.  
  94.                         datatable.Rows.Add(dr);  
  95.                     }  
  96.                 }  
  97.             }  
  98.             catch (Exception ex)  
  99.             {  
  100.                 // Info.  
  101.                 throw ex;  
  102.             }  
  103.             finally  
  104.             {  
  105.                 // Closing.  
  106.                 sr.Dispose();  
  107.                 sr.Close();  
  108.             }  
  109.   
  110.             // Info.  
  111.             return datatable;  
  112.         }  
  113.  
  114.         #endregion  
  115.  
  116.         #region Export Data method.  
  117.   
  118.         /// <summary>  
  119.         /// Export Data method.  
  120.         /// </summary>  
  121.         /// <param name="destFilePath">Destination file path parameter</param>  
  122.         /// <param name="dataTable">Data table parameter</param>  
  123.         /// <returns>Returns - True if save successfully</returns>  
  124.         public static bool Export(string destFilePath, DataTable dataTable)  
  125.         {  
  126.             // Initilization  
  127.             bool isSuccess = false;  
  128.             StreamWriter sw = null;  
  129.   
  130.             try  
  131.             {  
  132.                 // Initialization.  
  133.                 StringBuilder stringBuilder = new StringBuilder();  
  134.   
  135.                 // Saving Column header.  
  136.                 stringBuilder.Append(string.Join(",", dataTable.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToList()) + "\n");  
  137.   
  138.                 // Saving rows.  
  139.                 dataTable.AsEnumerable().ToList<DataRow>().ForEach(row => stringBuilder.Append(string.Join(",", row.ItemArray) + "\n"));  
  140.   
  141.                 // Initialization.  
  142.                 string fileContent = stringBuilder.ToString();  
  143.                 sw = new StreamWriter(new FileStream(destFilePath, FileMode.Create, FileAccess.Write));  
  144.   
  145.                 // Saving.  
  146.                 sw.Write(fileContent);  
  147.   
  148.                 // Settings.  
  149.                 isSuccess = true;  
  150.             }  
  151.             catch (Exception ex)  
  152.             {  
  153.                 // Info.  
  154.                 throw ex;  
  155.             }  
  156.             finally  
  157.             {  
  158.                 // Closing.  
  159.                 sw.Flush();  
  160.                 sw.Dispose();  
  161.                 sw.Close();  
  162.             }  
  163.   
  164.             // Info.  
  165.             return isSuccess;  
  166.         }  
  167.  
  168.         #endregion  
  169.     }  

In the above code, I have created an Import(...) method which will load the CSV file into a Datatable data structure. The fun fact about the Import(...) method is that it will automatically detect the number of columns in the CSV file. The last method is Export(...) method which will export the data from Datatable data structure to the target CSV file.
 
Step 3
 
Now, build the project and you will be able to see the "CSVLibraryAK.dll" file, which you can use in your different projects. You can install this library via NuGet packages or you can download pre-compiled DLL library or you can download the code and compile the DLL library files yourself.
 

Conclusion

 
In this article, you learned to create a simple C#.NET base class library for importing/exporting CSV data using Datatable as a primary data structure. You will also learn to auto-detect CSV file dynamic columns and you also learned to adjust CSV file header depending on the provided header information.