Header Ads

C#.Net Import/Export CSV Library

Importing/Exporting are some of the basic operations used in any sort of development. So, do this purpose I have created a very simple C#.NET library for importing/exporting CSV data using Datatable as a primary data structure. You can use this library into your any C#.NET project that supports Datatable data structure. This library imports CSV file with or without header and with any number of columns into C#.NET Datatable structure. The import function will automatically detects the number of columns of the CSV file. 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.


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-compile 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.

Code Download Link Nuget Installation Link

Let's begin now.

1) Create a new Windows Desktop -> Class Library (.NET Framework) project and name it "CSVLibraryAK".

2) Create "CSVLibraryAK.cs" file and replace following code in it i.e.

//-----------------------------------------------------------------------
// <copyright file="CSVLibraryAK.cs" company="None">
//     Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
// </copyright>
// <author>Asma Khalid</author>
//-----------------------------------------------------------------------

namespace CSVLibraryAK
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Web;
    using Resources.Constants;

    /// <summary>
    /// CSV library class.
    /// </summary>
    public class CSVLibraryAK
    {
        #region Import Data method.

        /// <summary>
        /// Import Data method.
        /// </summary>
        /// <param name="srcFilePath">Source file path parameter</param>
        /// <param name="hasHeader">Has header parameter</param>
        /// <returns>Returns CSV data as data table</returns>
        public static DataTable Import(string srcFilePath, bool hasHeader)
        {
            // Initilization
            DataTable datatable = new DataTable();
            StreamReader sr = null;

            try
            {
                // Creating data table without header.
                using (sr = new StreamReader(new FileStream(srcFilePath, FileMode.Open, FileAccess.Read)))
                {
                    // Initialization.
                    string line = string.Empty;
                    string[] headers = sr.ReadLine().Split(',');
                    DataRow dr = datatable.NewRow();

                    // Preparing header.
                    for (int i = 0; i < headers.Length; i++)
                    {
                        // Verification.
                        if (hasHeader)
                        {
                            // Setting.
                            datatable.Columns.Add(headers[i]);
                        }
                        else
                        {
                            // Setting.
                            datatable.Columns.Add(Strings.COL_HEADER_1 + i);
                            dr[i] = headers[i];
                        }
                    }

                    // Verification.
                    if (!hasHeader)
                    {
                        // Adding.
                        datatable.Rows.Add(dr);
                    }

                    // Adding data.
                    while ((line = sr.ReadLine()) != null)
                    {
                        // Initialization.
                        string[] rows = line.Split(',');
                        dr = datatable.NewRow();

                        // Verification
                        if (string.IsNullOrEmpty(line))
                        {
                            // Info.
                            continue;
                        }

                        // Adding row.
                        for (int i = 0; i < headers.Length; i++)
                        {
                            // Setting.
                            dr[i] = rows[i];
                        }

                        // Adding.
                        datatable.Rows.Add(dr);
                    }
                }
            }
            catch (Exception ex)
            {
                // Info.
                throw ex;
            }
            finally
            {
                // Closing.
                sr.Dispose();
                sr.Close();
            }

            // Info.
            return datatable;
        }

        #endregion

        #region Export Data method.

        /// <summary>
        /// Export Data method.
        /// </summary>
        /// <param name="destFilePath">Destination file path parameter</param>
        /// <param name="dataTable">Data table parameter</param>
        /// <returns>Returns - True if save successfully</returns>
        public static bool Export(string destFilePath, DataTable dataTable)
        {
            // Initilization
            bool isSuccess = false;
            StreamWriter sw = null;

            try
            {
                // Initialization.
                StringBuilder stringBuilder = new StringBuilder();

                // Saving Column header.
                stringBuilder.Append(string.Join(",", dataTable.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToList()) + "\n");

                // Saving rows.
                dataTable.AsEnumerable().ToList<DataRow>().ForEach(row => stringBuilder.Append(string.Join(",", row.ItemArray) + "\n"));

                // Initialization.
                string fileContent = stringBuilder.ToString();
                sw = new StreamWriter(new FileStream(destFilePath, FileMode.Create, FileAccess.Write));

                // Saving.
                sw.Write(fileContent);

                // Settings.
                isSuccess = true;
            }
            catch (Exception ex)
            {
                // Info.
                throw ex;
            }
            finally
            {
                // Closing.
                sw.Flush();
                sw.Dispose();
                sw.Close();
            }

            // Info.
            return isSuccess;
        }

        #endregion
    }
}

In the above code, I have created Import(...) method which will load the CSV file into Datatable data structure, the fun fact about the Import(...) method is that it will automatically detect the number of columns in CSV file. The last method is Export(...) method, which will export the data from Datatable data structure to target CSV file.

3) Now, Build the project and you will be able to see "CSVLibraryAK.dll" file, which you can use in your different projects. You can install this library via Nuget packages or you can download pre-compile DLL library or you can download the code and compile the DLL library file yourself

Conclusion

In this article, you will learn 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 will also learn to adjust CSV file header depend on provided has header information.

No comments