How to Upload a CSV file in C# Windows Form Application

Description

   In this article, I am going to write C# Windows Form Application code sample to Read or Upload CSV file into Windows Form DataGridView using OpenFileDialog Control to get or browse csv file path and TextFieldParser class from Microsoft.VisualBasic to parse CSV file content.

Summary

Upload CSV file in C# Windows Form Application – Form Designer

   Here, we have used .NET’s OpenFileDialog control to browse CSV file location and DataGridView control to show Imported CSV file data.

Import a CSV file in C# Windows Form Application
//CSVImporter.Designer.cs
-------------------------
partial class CSVImporter
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.tbCSVPath = new System.Windows.Forms.TextBox();
            this.btBrowse = new System.Windows.Forms.Button();
            this.btUpload = new System.Windows.Forms.Button();
            this.dgCSVData = new System.Windows.Forms.DataGridView();
            ((System.ComponentModel.ISupportInitialize)(this.dgCSVData)).BeginInit();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(23, 52);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(50, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "File path:";
            // 
            // tbCSVPath
            // 
            this.tbCSVPath.Location = new System.Drawing.Point(76, 50);
            this.tbCSVPath.Name = "tbCSVPath";
            this.tbCSVPath.Size = new System.Drawing.Size(345, 20);
            this.tbCSVPath.TabIndex = 1;
            // 
            // btBrowse
            // 
            this.btBrowse.Location = new System.Drawing.Point(437, 48);
            this.btBrowse.Name = "btBrowse";
            this.btBrowse.Size = new System.Drawing.Size(101, 23);
            this.btBrowse.TabIndex = 2;
            this.btBrowse.Text = "Browse";
            this.btBrowse.UseVisualStyleBackColor = true;
            this.btBrowse.Click += new System.EventHandler(this.btBrowse_Click);
            // 
            // btUpload
            // 
            this.btUpload.Location = new System.Drawing.Point(76, 76);
            this.btUpload.Name = "btUpload";
            this.btUpload.Size = new System.Drawing.Size(101, 23);
            this.btUpload.TabIndex = 3;
            this.btUpload.Text = "Upload CSV";
            this.btUpload.UseVisualStyleBackColor = true;
            this.btUpload.Click += new System.EventHandler(this.btUpload_Click);
            // 
            // dgCSVData
            // 
            this.dgCSVData.AllowUserToAddRows = false;
            this.dgCSVData.AllowUserToDeleteRows = false;
            this.dgCSVData.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgCSVData.Location = new System.Drawing.Point(26, 129);
            this.dgCSVData.Name = "dgCSVData";
            this.dgCSVData.ReadOnly = true;
            this.dgCSVData.Size = new System.Drawing.Size(512, 129);
            this.dgCSVData.TabIndex = 4;
            // 
            // CSVImporter
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(552, 268);
            this.Controls.Add(this.dgCSVData);
            this.Controls.Add(this.btUpload);
            this.Controls.Add(this.btBrowse);
            this.Controls.Add(this.tbCSVPath);
            this.Controls.Add(this.label1);
            this.Name = "CSVImporter";
            this.Text = "CSVImporter";
            ((System.ComponentModel.ISupportInitialize)(this.dgCSVData)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox tbCSVPath;
        private System.Windows.Forms.Button btBrowse;
        private System.Windows.Forms.Button btUpload;
        private System.Windows.Forms.DataGridView dgCSVData;
    }

Read CSV file in C# Windows Form using TextFieldParser

   We can read data from CSV file in many of custom ways. In this article, we are going to read or import data from CSV file into .NET DataTable by using TextFieldParser. don’t try to search this class in C# library because which is not available in C#. TextFieldParser is the Visual basic class. So we need to add reference dll Microsoft.VisualBasic.

  • Right-click the Reference, click Add Reference,select Microsoft.VisualBasic, and click OK button
Import CSV file in ASP.NET
private static DataTable GetDataTableFromCSVFile(string csvfilePath)
{
    DataTable csvData = new DataTable();
    using (TextFieldParser csvReader = new TextFieldParser(csvfilePath))
    {
        csvReader.SetDelimiters(new string[] { "," });
        csvReader.HasFieldsEnclosedInQuotes = true;

        //Read columns from CSV file, remove this line if columns not exits  
        string[] colFields = csvReader.ReadFields();

        foreach (string column in colFields)
        {
            DataColumn datecolumn = new DataColumn(column);
            datecolumn.AllowDBNull = true;
            csvData.Columns.Add(datecolumn);
        }

        while (!csvReader.EndOfData)
        {
            string[] fieldData = csvReader.ReadFields();
            //Making empty value as null
            for (int i = 0; i < fieldData.Length; i++)
            {
                if (fieldData[i] == "")
                {
                    fieldData[i] = null;
                }
            }
            csvData.Rows.Add(fieldData);
        }
    }
    return csvData;
}

Upload CSV file into Windows Form DataGridView – CodeBehind

   This is the C# Windows Form CodeBehind to read or import CSV file into Windows Form GridView. The OpenFileDialog control will help you browse the CSV file location, and here you can also type the CSV file path manually instead of using this OpenFileDialog control to browse CSV path.  Here, we have used filter  “|*.csv” in OpenFileDialog to list only csv files.

Note: Do not forgot to include the Reference Microsoft.VisualBasic to use TextFieldParser class.

//CSVImporter.cs
----------------------------

using System;
using System.Data;
using System.Windows.Forms;
using Microsoft.VisualBasic.FileIO;

namespace WinFormApp
{
    public partial class CSVImporter : Form
    {
        public CSVImporter()
        {
            InitializeComponent();
        }

        private void btBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            // To list only csv files, we need to add this filter
            openFileDialog.Filter = "|*.csv";
            DialogResult result = openFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                tbCSVPath.Text = openFileDialog.FileName;
            }
        }

        private void btUpload_Click(object sender, EventArgs e)
        {
            try
            {
                dgCSVData.DataSource = GetDataTableFromCSVFile(tbCSVPath.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Import CSV File", MessageBoxButtons.OK, 
  MessageBoxIcon.Error);
            }
        }

        private static DataTable GetDataTableFromCSVFile(string csvfilePath)
        {
            DataTable csvData = new DataTable();
            using (TextFieldParser csvReader = new TextFieldParser(csvfilePath))
            {
                csvReader.SetDelimiters(new string[] { "," });
                csvReader.HasFieldsEnclosedInQuotes = true;

                //Read columns from CSV file, remove this line if columns not exits  
                string[] colFields = csvReader.ReadFields();

                foreach (string column in colFields)
                {
                    DataColumn datecolumn = new DataColumn(column);
                    datecolumn.AllowDBNull = true;
                    csvData.Columns.Add(datecolumn);
                }

                while (!csvReader.EndOfData)
                {
                    string[] fieldData = csvReader.ReadFields();
                    //Making empty value as null
                    for (int i = 0; i < fieldData.Length; i++)
                    {
                        if (fieldData[i] == "")
                        {
                            fieldData[i] = null;
                        }
                    }
                    csvData.Rows.Add(fieldData);
                }
            }
            return csvData;
        }       
    }
}

Note: Here, we have assumed the CSV File’s first line is column header, so that we are reading columns  by this line:

                string[] colFields = csvReader.ReadFields();

If your CSV file don’t have the column header, you can just remove this line.

Output

 – After compiled the Windows Form project in Visual Studio, run the project by clicking CTRL + F5.
 – Click Browse button to browse CSV file and Upload CSV button to upload CSV file content into DataGridView

How to Read or Import a CSV file in C# Windows Form Application

Thanks,
Morgan
Software Developer


Advertisement

9 thoughts on “How to Upload a CSV file in C# Windows Form Application”

  1. I have doubt here there are three files 1. Form1.cs (code file we get when clicked view code on form).
    2. Form1.Designer.cs (with partial class)
    3.C# Program.cs (with main() )
    I want to know the use of Program.cs

    Reply
    • Hi Farhan, Program.cs–main() is the root entry class of Executing Application.
      When we run the Application the main (string [] args ) function will be triggered at initially..then in that main function, we can set which Form should be open first .

      in our case — Application.Run(new CSVImporter());
      so it will run/open the CSVImporter form

      Reply
  2. Instead of using the using Microsoft.VisualBasic.FileIO; you can try

    using System.IO;

    and then

    private static DataTable GetDataTableFromCSVFile(string csvfilePath)
    {
    DataTable csvData = new DataTable();

    DataTable dataTable = new DataTable();

    StreamReader streamReader = new StreamReader(csvfilePath);
    string[] totalData = new string[File.ReadAllLines(csvfilePath).Length];

    totalData = streamReader.ReadLine().Split(';');

    foreach (string column in totalData)
    {
    DataColumn datecolumn = new DataColumn(column);
    datecolumn.AllowDBNull = true;
    csvData.Columns.Add(datecolumn);
    }

    while (!streamReader.EndOfStream)
    {
    totalData = streamReader.ReadLine().Split(';');
    csvData.Rows.Add(totalData);
    }

    return csvData;
    }

    Reply
  3. hi
    my csv file without header i remove this line string[] colFields = csvReader.ReadFields();
    but its not work and what put instance colfields in (foreach (string column in colFields)) statment

    Reply
  4. this csv file

    001,0000002226,01,2011/03/27,07:07,
    001,0000009392,01,2011/03/27,07:12,
    001,0000002220,01,2011/03/27,07:17,
    001,0000002121,01,2011/03/27,07:19,

    Reply
    • Hi if your csv file is without header, you need to define your own column fields string [] colFields =new string []{"col1","col2","col3","col4","col5"}

      Reply

Leave a Comment