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

  1. using System.IO;
  2. using System.Text.RegularExpressions;
  3. using System.Data;
  4. public sealed class CsvReader: System.IDisposable {
  5. public CsvReader(string fileName): this(new FileStream(fileName, FileMode.Open, FileAccess.Read)) {}
  6. public CsvReader(Stream stream) {
  7. __reader = new StreamReader(stream);
  8. }
  9. public DataSet RowEnumerator {
  10. get {
  11. if (null == __reader) throw new System.ApplicationException("I can't start reading without CSV input.");
  12. __rowno = 0;
  13. string sLine;
  14. string sNextLine;
  15. DataSet ds = new DataSet();
  16. DataTable dt = ds.Tables.Add("TheData");
  17. while (null != (sLine = __reader.ReadLine())) {
  18. while (rexRunOnLine.IsMatch(sLine) && null != (sNextLine = __reader.ReadLine()))
  19. sLine += "\n" + sNextLine;
  20. __rowno++;
  21. DataRow dr = dt.NewRow();
  22. string[] values = rexCsvSplitter.Split(sLine);
  23. for (int i = 0; i < values.Length; i++) {
  24. values[i] = Csv.Unescape(values[i]);
  25. if (__rowno == 1) {
  26. dt.Columns.Add(values[i].Trim());
  27. } else {
  28. if (Csv.CharNotAllowes(values[i])) {
  29. dr[i] = values[i].Trim();
  30. }
  31. }
  32. }
  33. if (__rowno != 1) {
  34. dt.Rows.Add(dr);
  35. }
  36. //yield return values;
  37. }
  38. __reader.Close();
  39. return ds;
  40. }
  41. }
  42. public long RowIndex {
  43. get {
  44. return __rowno;
  45. }
  46. }
  47. public void Dispose() {
  48. if (null != __reader) __reader.Dispose();
  49. }
  50. //============================================
  51. private long __rowno = 0;
  52. private TextReader __reader;
  53. private static Regex rexCsvSplitter = new Regex(@
  54. ",(?=(?:[^"
  55. "]*"
  56. "[^"
  57. "]*"
  58. ")*(?![^"
  59. "]*"
  60. "))");
  61. private static Regex rexRunOnLine = new Regex(@
  62. "^[^"
  63. "]*(?:"
  64. "[^"
  65. "]*"
  66. "[^"
  67. "]*)*"
  68. "[^"
  69. "]*$");
  70. }
  71. public static class Csv {
  72. public static string Escape(string s) {
  73. if (s.Contains(QUOTE)) s = s.Replace(QUOTE, ESCAPED_QUOTE);
  74. if (s.IndexOfAny(CHARACTERS_THAT_MUST_BE_QUOTED) > -1) s = QUOTE + s + QUOTE;
  75. return s;
  76. }
  77. public static string Unescape(string s) {
  78. if (s.StartsWith(QUOTE) && s.EndsWith(QUOTE)) {
  79. s = s.Substring(1, s.Length - 2);
  80. if (s.Contains(ESCAPED_QUOTE)) s = s.Replace(ESCAPED_QUOTE, QUOTE);
  81. }
  82. return s;
  83. }
  84. public static bool CharNotAllowes(string s) {
  85. if (s.IndexOfAny(CHARACTERS_THAT_NOT_ALLOWED) > -1) {
  86. return false;
  87. } else {
  88. return true;
  89. }
  90. }
  91. private const string QUOTE = "\"";
  92. private const string ESCAPED_QUOTE = "\"\"";
  93. private static char[] CHARACTERS_THAT_MUST_BE_QUOTED = {
  94. ',', '"', '\n'
  95. };
  96. private static char[] CHARACTERS_THAT_NOT_ALLOWED = {
  97. '?', '!', '^', '*', '~', 'Ñ', '½', 'Ð', '', '»', 'µ', 'º', 'Ñ', '´'
  98. };
  99. }
Step 2: Create Design


Figure 1: CSV Reader

Step 3: Write Code
  1. using System;
  2. using System.Drawing;
  3. using System.Collections;
  4. using System.ComponentModel;
  5. using System.Windows.Forms;
  6. using System.Data;
  7. using System.Data.SqlClient;
  8. using System.Data.Odbc;
  9. using System.IO;
  10. using System.Data.OleDb;
  11. namespace Upload_Stock_Data {
  12. /// <summary>
  13. /// Summary description for frmMain.
  14. /// </summary>
  15. public class frmMain: System.Windows.Forms.Form
  16. {
  17. #region Declarations
  18. private System.Windows.Forms.GroupBox gbMain;
  19. private System.Windows.Forms.TextBox txtCSVFolderPath;
  20. private System.Windows.Forms.Button btnOpenFldrBwsr;
  21. private System.Windows.Forms.FolderBrowserDialog fbdCSVFolder;
  22. private System.Windows.Forms.TextBox txtCSVFilePath;
  23. private System.Windows.Forms.Button btnOpenFileDlg;
  24. private System.Windows.Forms.OpenFileDialog openFileDialogCSVFilePath;
  25. private System.Windows.Forms.Button btnImport;
  26. private System.Windows.Forms.DataGrid dGridCSVdata;
  27. string strCSVFile = "";
  28. private System.Windows.Forms.GroupBox gbMainUploadData;
  29. private System.Windows.Forms.Button btnUpload;
  30. System.Data.Odbc.OdbcDataAdapter obj_oledb_da;
  31. private bool bolColName = true;
  32. string strFormat = "CSVDelimited";
  33. private System.Windows.Forms.Label lblFolderPath;
  34. private System.Windows.Forms.Label lblFilePath;
  35. /// <summary>
  36. /// Required designer variable.
  37. /// </summary>
  38. private System.ComponentModel.Container components = null;#endregion
  39. #region Constructor
  40. public frmMain() {
  41. //
  42. // Required for Windows Form Designer support
  43. //
  44. InitializeComponent();
  45. //
  46. // TODO: Add any constructor code after InitializeComponent call
  47. //
  48. }#endregion
  49. #region Destructor
  50. /// <summary>
  51. /// Clean up any resources being used.
  52. /// </summary>
  53. protected override void Dispose(bool disposing) {
  54. if (disposing) {
  55. if (components != null) {
  56. components.Dispose();
  57. }
  58. }
  59. base.Dispose(disposing);
  60. }
  61. #endregion
  62. #region Windows Form Designer generated code
  63. /// <summary>
  64. /// Required method for Designer support - do not modify
  65. /// the contents of this method with the code editor.
  66. /// </summary>
  67. private void InitializeComponent() {
  68. this.gbMain = new System.Windows.Forms.GroupBox();
  69. this.lblFilePath = new System.Windows.Forms.Label();
  70. this.lblFolderPath = new System.Windows.Forms.Label();
  71. this.dGridCSVdata = new System.Windows.Forms.DataGrid();
  72. this.btnImport = new System.Windows.Forms.Button();
  73. this.btnOpenFileDlg = new System.Windows.Forms.Button();
  74. this.txtCSVFilePath = new System.Windows.Forms.TextBox();
  75. this.btnOpenFldrBwsr = new System.Windows.Forms.Button();
  76. this.txtCSVFolderPath = new System.Windows.Forms.TextBox();
  77. this.fbdCSVFolder = new System.Windows.Forms.FolderBrowserDialog();
  78. this.openFileDialogCSVFilePath = new System.Windows.Forms.OpenFileDialog();
  79. this.gbMainUploadData = new System.Windows.Forms.GroupBox();
  80. this.btnUpload = new System.Windows.Forms.Button();
  81. this.gbMain.SuspendLayout();
  82. ((System.ComponentModel.ISupportInitialize)(this.dGridCSVdata)).BeginInit();
  83. this.gbMainUploadData.SuspendLayout();
  84. this.SuspendLayout();
  85. //
  86. // gbMain
  87. //
  88. this.gbMain.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
  89. this.gbMain.Controls.Add(this.lblFilePath);
  90. this.gbMain.Controls.Add(this.lblFolderPath);
  91. this.gbMain.Controls.Add(this.dGridCSVdata);
  92. this.gbMain.Controls.Add(this.btnImport);
  93. this.gbMain.Controls.Add(this.btnOpenFileDlg);
  94. this.gbMain.Controls.Add(this.txtCSVFilePath);
  95. this.gbMain.Controls.Add(this.btnOpenFldrBwsr);
  96. this.gbMain.Controls.Add(this.txtCSVFolderPath);
  97. this.gbMain.FlatStyle = System.Windows.Forms.FlatStyle.System;
  98. this.gbMain.Location = new System.Drawing.Point(16, 8);
  99. this.gbMain.Name = "gbMain";
  100. this.gbMain.Size = new System.Drawing.Size(504, 416);
  101. this.gbMain.TabIndex = 0;
  102. this.gbMain.TabStop = false;
  103. this.gbMain.Text = "Import CSV Data";
  104. //
  105. // lblFilePath
  106. //
  107. this.lblFilePath.Location = new System.Drawing.Point(32, 47);
  108. this.lblFilePath.Name = "lblFilePath";
  109. this.lblFilePath.Size = new System.Drawing.Size(72, 20);
  110. this.lblFilePath.TabIndex = 12;
  111. this.lblFilePath.Text = "File Path:";
  112. this.lblFilePath.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
  113. //
  114. // lblFolderPath
  115. //
  116. this.lblFolderPath.Location = new System.Drawing.Point(32, 23);
  117. this.lblFolderPath.Name = "lblFolderPath";
  118. this.lblFolderPath.Size = new System.Drawing.Size(72, 20);
  119. this.lblFolderPath.TabIndex = 11;
  120. this.lblFolderPath.Text = "Folder Path:";
  121. this.lblFolderPath.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
  122. //
  123. // dGridCSVdata
  124. //
  125. this.dGridCSVdata.AlternatingBackColor = System.Drawing.SystemColors.ControlLightLight;
  126. this.dGridCSVdata.CaptionForeColor = System.Drawing.Color.AliceBlue;
  127. this.dGridCSVdata.CaptionText = "Imported CSV Data";
  128. this.dGridCSVdata.DataMember = "";
  129. this.dGridCSVdata.ForeColor = System.Drawing.Color.YellowGreen;
  130. this.dGridCSVdata.HeaderBackColor = System.Drawing.Color.BlanchedAlmond;
  131. this.dGridCSVdata.HeaderForeColor = System.Drawing.Color.Black;
  132. this.dGridCSVdata.Location = new System.Drawing.Point(8, 124);
  133. this.dGridCSVdata.Name = "dGridCSVdata";
  134. this.dGridCSVdata.ParentRowsForeColor = System.Drawing.Color.Yellow;
  135. this.dGridCSVdata.ReadOnly = true;
  136. this.dGridCSVdata.SelectionForeColor = System.Drawing.SystemColors.ControlLight;
  137. this.dGridCSVdata.Size = new System.Drawing.Size(488, 276);
  138. this.dGridCSVdata.TabIndex = 5;
  139. //
  140. // btnImport
  141. //
  142. this.btnImport.Cursor = System.Windows.Forms.Cursors.Hand;
  143. this.btnImport.FlatStyle = System.Windows.Forms.FlatStyle.System;
  144. this.btnImport.Location = new System.Drawing.Point(112, 92);
  145. this.btnImport.Name = "btnImport";
  146. this.btnImport.Size = new System.Drawing.Size(280, 26);
  147. this.btnImport.TabIndex = 4;
  148. this.btnImport.Text = "Import CSV Data";
  149. this.btnImport.Click += new System.EventHandler(this.btnImport_Click);
  150. //
  151. // btnOpenFileDlg
  152. //
  153. this.btnOpenFileDlg.Cursor = System.Windows.Forms.Cursors.Hand;
  154. this.btnOpenFileDlg.FlatStyle = System.Windows.Forms.FlatStyle.System;
  155. this.btnOpenFileDlg.Location = new System.Drawing.Point(368, 47);
  156. this.btnOpenFileDlg.Name = "btnOpenFileDlg";
  157. this.btnOpenFileDlg.Size = new System.Drawing.Size(24, 23);
  158. this.btnOpenFileDlg.TabIndex = 3;
  159. this.btnOpenFileDlg.Click += new System.EventHandler(this.btnOpenFileDlg_Click);
  160. //
  161. // txtCSVFilePath
  162. //
  163. this.txtCSVFilePath.BackColor = System.Drawing.SystemColors.Info;
  164. this.txtCSVFilePath.Location = new System.Drawing.Point(112, 48);
  165. this.txtCSVFilePath.Name = "txtCSVFilePath";
  166. this.txtCSVFilePath.ReadOnly = true;
  167. this.txtCSVFilePath.Size = new System.Drawing.Size(240, 20);
  168. this.txtCSVFilePath.TabIndex = 2;
  169. this.txtCSVFilePath.Text = "D:\\Test\\Test.csv";
  170. //
  171. // btnOpenFldrBwsr
  172. //
  173. this.btnOpenFldrBwsr.Cursor = System.Windows.Forms.Cursors.Hand;
  174. this.btnOpenFldrBwsr.FlatStyle = System.Windows.Forms.FlatStyle.System;
  175. this.btnOpenFldrBwsr.Location = new System.Drawing.Point(368, 24);
  176. this.btnOpenFldrBwsr.Name = "btnOpenFldrBwsr";
  177. this.btnOpenFldrBwsr.Size = new System.Drawing.Size(24, 23);
  178. this.btnOpenFldrBwsr.TabIndex = 1;
  179. this.btnOpenFldrBwsr.Click += new System.EventHandler(this.btnOpenFldrBwsr_Click);
  180. //
  181. // txtCSVFolderPath
  182. //
  183. this.txtCSVFolderPath.BackColor = System.Drawing.SystemColors.Info;
  184. this.txtCSVFolderPath.Location = new System.Drawing.Point(112, 24);
  185. this.txtCSVFolderPath.Name = "txtCSVFolderPath";
  186. this.txtCSVFolderPath.ReadOnly = true;
  187. this.txtCSVFolderPath.Size = new System.Drawing.Size(240, 20);
  188. this.txtCSVFolderPath.TabIndex = 1;
  189. this.txtCSVFolderPath.Text = "D:\\Test";
  190. //
  191. // openFileDialogCSVFilePath
  192. //
  193. this.openFileDialogCSVFilePath.Filter = "CSV Files (*.csv)|*.csv|DAT Files (*.dat)|*.dat";
  194. this.openFileDialogCSVFilePath.Title = "Select the CSV file for importing";
  195. this.openFileDialogCSVFilePath.FileOk += new System.ComponentModel.CancelEventHandler(this.openFileDialogCSVFilePath_FileOk);
  196. //
  197. // gbMainUploadData
  198. //
  199. this.gbMainUploadData.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
  200. this.gbMainUploadData.Controls.Add(this.btnUpload);
  201. this.gbMainUploadData.FlatStyle = System.Windows.Forms.FlatStyle.System;
  202. this.gbMainUploadData.Location = new System.Drawing.Point(16, 432);
  203. this.gbMainUploadData.Name = "gbMainUploadData";
  204. this.gbMainUploadData.Size = new System.Drawing.Size(504, 56);
  205. this.gbMainUploadData.TabIndex = 1;
  206. this.gbMainUploadData.TabStop = false;
  207. this.gbMainUploadData.Text = "Save Data in Table";
  208. //
  209. // btnUpload
  210. //
  211. this.btnUpload.Cursor = System.Windows.Forms.Cursors.Hand;
  212. this.btnUpload.Enabled = false;
  213. this.btnUpload.FlatStyle = System.Windows.Forms.FlatStyle.System;
  214. this.btnUpload.Location = new System.Drawing.Point(112, 24);
  215. this.btnUpload.Name = "btnUpload";
  216. this.btnUpload.Size = new System.Drawing.Size(280, 23);
  217. this.btnUpload.TabIndex = 1;
  218. this.btnUpload.Text = "Save";
  219. this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
  220. //
  221. // frmMain
  222. //
  223. this.AcceptButton = this.btnImport;
  224. this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
  225. this.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
  226. this.ClientSize = new System.Drawing.Size(536, 494);
  227. this.Controls.Add(this.gbMainUploadData);
  228. this.Controls.Add(this.gbMain);
  229. this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
  230. this.MaximizeBox = false;
  231. this.Name = "frmMain";
  232. this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
  233. this.Text = "CSV Reader";
  234. this.Closing += new System.ComponentModel.CancelEventHandler(this.frmMain_Closing);
  235. this.Load += new System.EventHandler(this.frmMain_Load);
  236. this.gbMain.ResumeLayout(false);
  237. this.gbMain.PerformLayout();
  238. ((System.ComponentModel.ISupportInitialize)(this.dGridCSVdata)).EndInit();
  239. this.gbMainUploadData.ResumeLayout(false);
  240. this.ResumeLayout(false);
  241. }#endregion
  242. #region Main() Method
  243. /// <summary>
  244. /// The main entry point for the application.
  245. /// </summary>
  246. [STAThread]
  247. static void Main() {
  248. Application.EnableVisualStyles();
  249. Application.DoEvents();
  250. Application.Run(new frmMain());
  251. }#endregion
  252. #region Form Load
  253. private void frmMain_Load(object sender, System.EventArgs e) {
  254. try {
  255. } catch (Exception ex) {
  256. MessageBox.Show(ex.Message);
  257. } finally {}
  258. }#endregion
  259. #region Open Folder Browser Button
  260. // On click of this button, the FOLDERBROWSERDIALOG opens where user can select the path of the folder
  261. // containing .csv files
  262. private void btnOpenFldrBwsr_Click(object sender, System.EventArgs e) {
  263. try {
  264. if (fbdCSVFolder.ShowDialog() == DialogResult.OK) {
  265. txtCSVFolderPath.Text = fbdCSVFolder.SelectedPath.Trim();
  266. }
  267. } catch (Exception ex) {
  268. MessageBox.Show(ex.Message);
  269. } finally {
  270. }
  271. }#endregion
  272. #region Open File Dialog Button
  273. // On click of this button, the openfiledialog opens where user can select .csv file
  274. private void btnOpenFileDlg_Click(object sender, System.EventArgs e) {
  275. try {
  276. openFileDialogCSVFilePath.InitialDirectory = txtCSVFolderPath.Text.Trim();
  277. if (openFileDialogCSVFilePath.ShowDialog() == DialogResult.OK) {
  278. txtCSVFilePath.Text = openFileDialogCSVFilePath.FileName.Trim();
  279. }
  280. } catch (Exception ex) {
  281. MessageBox.Show(ex.Message);
  282. } finally {}
  283. }#endregion
  284. #region Function For Importing Data From CSV File
  285. public DataSet ConnectCSV() {
  286. DataSet ds = new DataSet();
  287. string fileName = openFileDialogCSVFilePath.FileName;
  288. CsvReader reader = new CsvReader(fileName);
  289. ds = reader.RowEnumerator;
  290. dGridCSVdata.DataSource = ds;
  291. dGridCSVdata.DataMember = "TheData";
  292. return ds;
  293. }
  294. #endregion
  295. #region Button Import CSV Data
  296. private void btnImport_Click(object sender, System.EventArgs e) {
  297. try {
  298. if (txtCSVFolderPath.Text == "") {
  299. MessageBox.Show("The Folder Path TextBox cannot be empty.", "Warning");
  300. return;
  301. } else if (txtCSVFilePath.Text == "") {
  302. MessageBox.Show("The File Path TextBox cannot be empty.", "Warning");
  303. return;
  304. } else {
  305. //int intLengthOfFileName = txtCSVFilePath.Text.Trim().Length;
  306. //int intLastIndex = txtCSVFilePath.Text.Trim().LastIndexOf("\\");
  307. //strCSVFile = txtCSVFilePath.Text.Trim().Substring(intLastIndex, intLengthOfFileName - intLastIndex);
  308. //strCSVFile = strCSVFile.Remove(0, 1).Trim();
  309. // writeSchema();
  310. ConnectCSV();
  311. btnUpload.Enabled = true;
  312. }
  313. } catch (Exception ex) {
  314. MessageBox.Show(ex.Message);
  315. } finally {}
  316. }#endregion
  317. #region Button Insert Data
  318. // Here we will insert the imported data in our database
  319. private void btnUpload_Click(object sender, System.EventArgs e) {
  320. try {
  321. // Create an SQL Connection
  322. //SqlConnection con1 = new SqlConnection(ReadConFile().Trim());
  323. OleDbConnection con1 = new OleDbConnection();
  324. con1.ConnectionString = @
  325. "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\\Users\\KML Surani\\Documents\\ImportCSV.accdb;Persist Security Info=False;";
  326. OleDbCommand cmd = new OleDbCommand();
  327. // Create Dataset
  328. DataSet da = new DataSet();
  329. // To actually fill the dataset, Call the function ImportCSV and assign the returned
  330. // dataset to new dataset as below
  331. da = this.ConnectCSV();
  332. // Now we will collect data from data table and insert it into database one by one
  333. // Initially there will be no data in database so we will insert data in first two columns
  334. // and after that we will update data in same row for remaining columns
  335. // The logic is simple. 'i' represents rows while 'j' represents columns
  336. con1.Open();
  337. cmd.Connection = con1;
  338. cmd.CommandType = CommandType.Text;
  339. for (int i = 0; i <= da.Tables["TheData"].Rows.Count - 1; i++) {
  340. cmd.CommandText = "Insert into tblImportCSV (Name,City) values('" + da.Tables["TheData"].Rows[i]["Name"] + "','" + da.Tables["TheData"].Rows[i]["City"] + "')";
  341. // For UPDATE statement, in where clause you need some unique row
  342. //identifier. We are using ‘srno’ in WHERE clause.
  343. //cmd1.CommandText = "Update Test set " + da.Tables["Stocks"].Columns[j].ColumnName.Trim() + " = '" + da.Tables["Stocks"].Rows[i].ItemArray.GetValue(j) + "' where srno =" + (i + 1);
  344. cmd.ExecuteNonQuery();
  345. //cmd1.ExecuteNonQuery();
  346. }
  347. con1.Close();
  348. } catch (Exception ex) {
  349. MessageBox.Show(ex.Message);
  350. } finally {
  351. btnUpload.Enabled = false;
  352. }
  353. }#endregion
  354. #region Form Closing
  355. private void frmMain_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
  356. try {
  357. Application.Exit();
  358. } catch (Exception ex) {
  359. MessageBox.Show(ex.Message);
  360. } finally {}
  361. }#endregion
  362. private void openFileDialogCSVFilePath_FileOk(object sender, CancelEventArgs e) {
  363. }
  364. }
  365. }
In the same way, you can also upload .xlsx file in desktop application.