Introduction
This blog is useful for uploading a CSV file in desktop application(C#) and store data in MS-Access Database. Also you can modify connection string and query useful for stored data in SQL Server.
Using The Code
Step 1: Create a class to upload CSV file.
CSVUpload.cs
- using System.IO;
- using System.Text.RegularExpressions;
- using System.Data;
- public sealed class CsvReader: System.IDisposable {
- public CsvReader(string fileName): this(new FileStream(fileName, FileMode.Open, FileAccess.Read)) {}
- public CsvReader(Stream stream) {
- __reader = new StreamReader(stream);
- }
- public DataSet RowEnumerator {
- get {
- if (null == __reader) throw new System.ApplicationException("I can't start reading without CSV input.");
- __rowno = 0;
- string sLine;
- string sNextLine;
- DataSet ds = new DataSet();
- DataTable dt = ds.Tables.Add("TheData");
- while (null != (sLine = __reader.ReadLine())) {
- while (rexRunOnLine.IsMatch(sLine) && null != (sNextLine = __reader.ReadLine()))
- sLine += "\n" + sNextLine;
- __rowno++;
- DataRow dr = dt.NewRow();
- string[] values = rexCsvSplitter.Split(sLine);
- for (int i = 0; i < values.Length; i++) {
- values[i] = Csv.Unescape(values[i]);
- if (__rowno == 1) {
- dt.Columns.Add(values[i].Trim());
- } else {
- if (Csv.CharNotAllowes(values[i])) {
- dr[i] = values[i].Trim();
- }
- }
- }
- if (__rowno != 1) {
- dt.Rows.Add(dr);
- }
-
- }
- __reader.Close();
- return ds;
- }
- }
- public long RowIndex {
- get {
- return __rowno;
- }
- }
- public void Dispose() {
- if (null != __reader) __reader.Dispose();
- }
-
- private long __rowno = 0;
- private TextReader __reader;
- private static Regex rexCsvSplitter = new Regex(@
- ",(?=(?:[^"
- "]*"
- "[^"
- "]*"
- ")*(?![^"
- "]*"
- "))");
- private static Regex rexRunOnLine = new Regex(@
- "^[^"
- "]*(?:"
- "[^"
- "]*"
- "[^"
- "]*)*"
- "[^"
- "]*$");
- }
- public static class Csv {
- public static string Escape(string s) {
- if (s.Contains(QUOTE)) s = s.Replace(QUOTE, ESCAPED_QUOTE);
- if (s.IndexOfAny(CHARACTERS_THAT_MUST_BE_QUOTED) > -1) s = QUOTE + s + QUOTE;
- return s;
- }
- public static string Unescape(string s) {
- if (s.StartsWith(QUOTE) && s.EndsWith(QUOTE)) {
- s = s.Substring(1, s.Length - 2);
- if (s.Contains(ESCAPED_QUOTE)) s = s.Replace(ESCAPED_QUOTE, QUOTE);
- }
- return s;
- }
- public static bool CharNotAllowes(string s) {
- if (s.IndexOfAny(CHARACTERS_THAT_NOT_ALLOWED) > -1) {
- return false;
- } else {
- return true;
- }
- }
- private const string QUOTE = "\"";
- private const string ESCAPED_QUOTE = "\"\"";
- private static char[] CHARACTERS_THAT_MUST_BE_QUOTED = {
- ',', '"', '\n'
- };
- private static char[] CHARACTERS_THAT_NOT_ALLOWED = {
- '?', '!', '^', '*', '~', 'Ñ', '½', 'Ð', '', '»', 'µ', 'º', 'Ñ', '´'
- };
- }
Step 2: Create Design
Figure 1: CSV Reader
Step 3: Write Code
- using System;
- using System.Drawing;
- using System.Collections;
- using System.ComponentModel;
- using System.Windows.Forms;
- using System.Data;
- using System.Data.SqlClient;
- using System.Data.Odbc;
- using System.IO;
- using System.Data.OleDb;
- namespace Upload_Stock_Data {
-
-
-
- public class frmMain: System.Windows.Forms.Form
- {
- #region Declarations
- private System.Windows.Forms.GroupBox gbMain;
- private System.Windows.Forms.TextBox txtCSVFolderPath;
- private System.Windows.Forms.Button btnOpenFldrBwsr;
- private System.Windows.Forms.FolderBrowserDialog fbdCSVFolder;
- private System.Windows.Forms.TextBox txtCSVFilePath;
- private System.Windows.Forms.Button btnOpenFileDlg;
- private System.Windows.Forms.OpenFileDialog openFileDialogCSVFilePath;
- private System.Windows.Forms.Button btnImport;
- private System.Windows.Forms.DataGrid dGridCSVdata;
- string strCSVFile = "";
- private System.Windows.Forms.GroupBox gbMainUploadData;
- private System.Windows.Forms.Button btnUpload;
- System.Data.Odbc.OdbcDataAdapter obj_oledb_da;
- private bool bolColName = true;
- string strFormat = "CSVDelimited";
- private System.Windows.Forms.Label lblFolderPath;
- private System.Windows.Forms.Label lblFilePath;
-
-
-
- private System.ComponentModel.Container components = null;#endregion
- #region Constructor
- public frmMain() {
-
-
-
- InitializeComponent();
-
-
-
-
- }#endregion
- #region Destructor
-
-
-
- protected override void Dispose(bool disposing) {
- if (disposing) {
- if (components != null) {
- components.Dispose();
- }
- }
- base.Dispose(disposing);
- }
- #endregion
- #region Windows Form Designer generated code
-
-
-
-
- private void InitializeComponent() {
- this.gbMain = new System.Windows.Forms.GroupBox();
- this.lblFilePath = new System.Windows.Forms.Label();
- this.lblFolderPath = new System.Windows.Forms.Label();
- this.dGridCSVdata = new System.Windows.Forms.DataGrid();
- this.btnImport = new System.Windows.Forms.Button();
- this.btnOpenFileDlg = new System.Windows.Forms.Button();
- this.txtCSVFilePath = new System.Windows.Forms.TextBox();
- this.btnOpenFldrBwsr = new System.Windows.Forms.Button();
- this.txtCSVFolderPath = new System.Windows.Forms.TextBox();
- this.fbdCSVFolder = new System.Windows.Forms.FolderBrowserDialog();
- this.openFileDialogCSVFilePath = new System.Windows.Forms.OpenFileDialog();
- this.gbMainUploadData = new System.Windows.Forms.GroupBox();
- this.btnUpload = new System.Windows.Forms.Button();
- this.gbMain.SuspendLayout();
- ((System.ComponentModel.ISupportInitialize)(this.dGridCSVdata)).BeginInit();
- this.gbMainUploadData.SuspendLayout();
- this.SuspendLayout();
-
-
-
- this.gbMain.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
- this.gbMain.Controls.Add(this.lblFilePath);
- this.gbMain.Controls.Add(this.lblFolderPath);
- this.gbMain.Controls.Add(this.dGridCSVdata);
- this.gbMain.Controls.Add(this.btnImport);
- this.gbMain.Controls.Add(this.btnOpenFileDlg);
- this.gbMain.Controls.Add(this.txtCSVFilePath);
- this.gbMain.Controls.Add(this.btnOpenFldrBwsr);
- this.gbMain.Controls.Add(this.txtCSVFolderPath);
- this.gbMain.FlatStyle = System.Windows.Forms.FlatStyle.System;
- this.gbMain.Location = new System.Drawing.Point(16, 8);
- this.gbMain.Name = "gbMain";
- this.gbMain.Size = new System.Drawing.Size(504, 416);
- this.gbMain.TabIndex = 0;
- this.gbMain.TabStop = false;
- this.gbMain.Text = "Import CSV Data";
-
-
-
- this.lblFilePath.Location = new System.Drawing.Point(32, 47);
- this.lblFilePath.Name = "lblFilePath";
- this.lblFilePath.Size = new System.Drawing.Size(72, 20);
- this.lblFilePath.TabIndex = 12;
- this.lblFilePath.Text = "File Path:";
- this.lblFilePath.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
-
-
-
- this.lblFolderPath.Location = new System.Drawing.Point(32, 23);
- this.lblFolderPath.Name = "lblFolderPath";
- this.lblFolderPath.Size = new System.Drawing.Size(72, 20);
- this.lblFolderPath.TabIndex = 11;
- this.lblFolderPath.Text = "Folder Path:";
- this.lblFolderPath.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
-
-
-
- this.dGridCSVdata.AlternatingBackColor = System.Drawing.SystemColors.ControlLightLight;
- this.dGridCSVdata.CaptionForeColor = System.Drawing.Color.AliceBlue;
- this.dGridCSVdata.CaptionText = "Imported CSV Data";
- this.dGridCSVdata.DataMember = "";
- this.dGridCSVdata.ForeColor = System.Drawing.Color.YellowGreen;
- this.dGridCSVdata.HeaderBackColor = System.Drawing.Color.BlanchedAlmond;
- this.dGridCSVdata.HeaderForeColor = System.Drawing.Color.Black;
- this.dGridCSVdata.Location = new System.Drawing.Point(8, 124);
- this.dGridCSVdata.Name = "dGridCSVdata";
- this.dGridCSVdata.ParentRowsForeColor = System.Drawing.Color.Yellow;
- this.dGridCSVdata.ReadOnly = true;
- this.dGridCSVdata.SelectionForeColor = System.Drawing.SystemColors.ControlLight;
- this.dGridCSVdata.Size = new System.Drawing.Size(488, 276);
- this.dGridCSVdata.TabIndex = 5;
-
-
-
- this.btnImport.Cursor = System.Windows.Forms.Cursors.Hand;
- this.btnImport.FlatStyle = System.Windows.Forms.FlatStyle.System;
- this.btnImport.Location = new System.Drawing.Point(112, 92);
- this.btnImport.Name = "btnImport";
- this.btnImport.Size = new System.Drawing.Size(280, 26);
- this.btnImport.TabIndex = 4;
- this.btnImport.Text = "Import CSV Data";
- this.btnImport.Click += new System.EventHandler(this.btnImport_Click);
-
-
-
- this.btnOpenFileDlg.Cursor = System.Windows.Forms.Cursors.Hand;
- this.btnOpenFileDlg.FlatStyle = System.Windows.Forms.FlatStyle.System;
- this.btnOpenFileDlg.Location = new System.Drawing.Point(368, 47);
- this.btnOpenFileDlg.Name = "btnOpenFileDlg";
- this.btnOpenFileDlg.Size = new System.Drawing.Size(24, 23);
- this.btnOpenFileDlg.TabIndex = 3;
- this.btnOpenFileDlg.Click += new System.EventHandler(this.btnOpenFileDlg_Click);
-
-
-
- this.txtCSVFilePath.BackColor = System.Drawing.SystemColors.Info;
- this.txtCSVFilePath.Location = new System.Drawing.Point(112, 48);
- this.txtCSVFilePath.Name = "txtCSVFilePath";
- this.txtCSVFilePath.ReadOnly = true;
- this.txtCSVFilePath.Size = new System.Drawing.Size(240, 20);
- this.txtCSVFilePath.TabIndex = 2;
- this.txtCSVFilePath.Text = "D:\\Test\\Test.csv";
-
-
-
- this.btnOpenFldrBwsr.Cursor = System.Windows.Forms.Cursors.Hand;
- this.btnOpenFldrBwsr.FlatStyle = System.Windows.Forms.FlatStyle.System;
- this.btnOpenFldrBwsr.Location = new System.Drawing.Point(368, 24);
- this.btnOpenFldrBwsr.Name = "btnOpenFldrBwsr";
- this.btnOpenFldrBwsr.Size = new System.Drawing.Size(24, 23);
- this.btnOpenFldrBwsr.TabIndex = 1;
- this.btnOpenFldrBwsr.Click += new System.EventHandler(this.btnOpenFldrBwsr_Click);
-
-
-
- this.txtCSVFolderPath.BackColor = System.Drawing.SystemColors.Info;
- this.txtCSVFolderPath.Location = new System.Drawing.Point(112, 24);
- this.txtCSVFolderPath.Name = "txtCSVFolderPath";
- this.txtCSVFolderPath.ReadOnly = true;
- this.txtCSVFolderPath.Size = new System.Drawing.Size(240, 20);
- this.txtCSVFolderPath.TabIndex = 1;
- this.txtCSVFolderPath.Text = "D:\\Test";
-
-
-
- this.openFileDialogCSVFilePath.Filter = "CSV Files (*.csv)|*.csv|DAT Files (*.dat)|*.dat";
- this.openFileDialogCSVFilePath.Title = "Select the CSV file for importing";
- this.openFileDialogCSVFilePath.FileOk += new System.ComponentModel.CancelEventHandler(this.openFileDialogCSVFilePath_FileOk);
-
-
-
- this.gbMainUploadData.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
- this.gbMainUploadData.Controls.Add(this.btnUpload);
- this.gbMainUploadData.FlatStyle = System.Windows.Forms.FlatStyle.System;
- this.gbMainUploadData.Location = new System.Drawing.Point(16, 432);
- this.gbMainUploadData.Name = "gbMainUploadData";
- this.gbMainUploadData.Size = new System.Drawing.Size(504, 56);
- this.gbMainUploadData.TabIndex = 1;
- this.gbMainUploadData.TabStop = false;
- this.gbMainUploadData.Text = "Save Data in Table";
-
-
-
- this.btnUpload.Cursor = System.Windows.Forms.Cursors.Hand;
- this.btnUpload.Enabled = false;
- this.btnUpload.FlatStyle = System.Windows.Forms.FlatStyle.System;
- this.btnUpload.Location = new System.Drawing.Point(112, 24);
- this.btnUpload.Name = "btnUpload";
- this.btnUpload.Size = new System.Drawing.Size(280, 23);
- this.btnUpload.TabIndex = 1;
- this.btnUpload.Text = "Save";
- this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
-
-
-
- this.AcceptButton = this.btnImport;
- this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
- this.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
- this.ClientSize = new System.Drawing.Size(536, 494);
- this.Controls.Add(this.gbMainUploadData);
- this.Controls.Add(this.gbMain);
- this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
- this.MaximizeBox = false;
- this.Name = "frmMain";
- this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
- this.Text = "CSV Reader";
- this.Closing += new System.ComponentModel.CancelEventHandler(this.frmMain_Closing);
- this.Load += new System.EventHandler(this.frmMain_Load);
- this.gbMain.ResumeLayout(false);
- this.gbMain.PerformLayout();
- ((System.ComponentModel.ISupportInitialize)(this.dGridCSVdata)).EndInit();
- this.gbMainUploadData.ResumeLayout(false);
- this.ResumeLayout(false);
- }#endregion
- #region Main() Method
-
-
-
- [STAThread]
- static void Main() {
- Application.EnableVisualStyles();
- Application.DoEvents();
- Application.Run(new frmMain());
- }#endregion
- #region Form Load
- private void frmMain_Load(object sender, System.EventArgs e) {
- try {
- } catch (Exception ex) {
- MessageBox.Show(ex.Message);
- } finally {}
- }#endregion
- #region Open Folder Browser Button
-
-
- private void btnOpenFldrBwsr_Click(object sender, System.EventArgs e) {
- try {
- if (fbdCSVFolder.ShowDialog() == DialogResult.OK) {
- txtCSVFolderPath.Text = fbdCSVFolder.SelectedPath.Trim();
- }
- } catch (Exception ex) {
- MessageBox.Show(ex.Message);
- } finally {
- }
- }#endregion
- #region Open File Dialog Button
-
- private void btnOpenFileDlg_Click(object sender, System.EventArgs e) {
- try {
- openFileDialogCSVFilePath.InitialDirectory = txtCSVFolderPath.Text.Trim();
- if (openFileDialogCSVFilePath.ShowDialog() == DialogResult.OK) {
- txtCSVFilePath.Text = openFileDialogCSVFilePath.FileName.Trim();
- }
- } catch (Exception ex) {
- MessageBox.Show(ex.Message);
- } finally {}
- }#endregion
- #region Function For Importing Data From CSV File
- public DataSet ConnectCSV() {
- DataSet ds = new DataSet();
- string fileName = openFileDialogCSVFilePath.FileName;
- CsvReader reader = new CsvReader(fileName);
- ds = reader.RowEnumerator;
- dGridCSVdata.DataSource = ds;
- dGridCSVdata.DataMember = "TheData";
- return ds;
- }
- #endregion
- #region Button Import CSV Data
- private void btnImport_Click(object sender, System.EventArgs e) {
- try {
- if (txtCSVFolderPath.Text == "") {
- MessageBox.Show("The Folder Path TextBox cannot be empty.", "Warning");
- return;
- } else if (txtCSVFilePath.Text == "") {
- MessageBox.Show("The File Path TextBox cannot be empty.", "Warning");
- return;
- } else {
-
-
-
-
-
- ConnectCSV();
- btnUpload.Enabled = true;
- }
- } catch (Exception ex) {
- MessageBox.Show(ex.Message);
- } finally {}
- }#endregion
- #region Button Insert Data
-
- private void btnUpload_Click(object sender, System.EventArgs e) {
- try {
-
-
- OleDbConnection con1 = new OleDbConnection();
- con1.ConnectionString = @
- "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\\Users\\KML Surani\\Documents\\ImportCSV.accdb;Persist Security Info=False;";
- OleDbCommand cmd = new OleDbCommand();
-
- DataSet da = new DataSet();
-
-
- da = this.ConnectCSV();
-
-
-
-
- con1.Open();
- cmd.Connection = con1;
- cmd.CommandType = CommandType.Text;
- for (int i = 0; i <= da.Tables["TheData"].Rows.Count - 1; i++) {
- cmd.CommandText = "Insert into tblImportCSV (Name,City) values('" + da.Tables["TheData"].Rows[i]["Name"] + "','" + da.Tables["TheData"].Rows[i]["City"] + "')";
-
-
-
- cmd.ExecuteNonQuery();
-
- }
- con1.Close();
- } catch (Exception ex) {
- MessageBox.Show(ex.Message);
- } finally {
- btnUpload.Enabled = false;
- }
- }#endregion
- #region Form Closing
- private void frmMain_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
- try {
- Application.Exit();
- } catch (Exception ex) {
- MessageBox.Show(ex.Message);
- } finally {}
- }#endregion
- private void openFileDialogCSVFilePath_FileOk(object sender, CancelEventArgs e) {
- }
- }
- }
In the same way, you can also upload .xlsx file in desktop application.