In this blog, I will show how to upload files to a folder using C# code. This will help you to understand the file upload feature in C#.
First, we have to create a WinForm like in the given image.
Here is the code for FileUpload.Designer.cs file.
  1. namespace FileUploads
  2. {
  3. partial class FileUpload
  4. {
  5. /// <summary>
  6. /// Required designer variable.
  7. /// </summary>
  8. private System.ComponentModel.IContainer components = null;
  9. /// <summary>
  10. /// Clean up any resources being used.
  11. /// </summary>
  12. /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  13. protected override void Dispose(bool disposing)
  14. {
  15. if (disposing && (components != null))
  16. {
  17. components.Dispose();
  18. }
  19. base.Dispose(disposing);
  20. }
  21. #region Windows Form Designer generated code
  22. /// <summary>
  23. /// Required method for Designer support - do not modify
  24. /// the contents of this method with the code editor.
  25. /// </summary>
  26. private void InitializeComponent()
  27. {
  28. this.btnFile = new System.Windows.Forms.Button();
  29. this.dgvFile = new System.Windows.Forms.DataGridView();
  30. this.fileName = new System.Windows.Forms.DataGridViewTextBoxColumn();
  31. this.filePath = new System.Windows.Forms.DataGridViewTextBoxColumn();
  32. this.fileSavePath = new System.Windows.Forms.DataGridViewTextBoxColumn();
  33. this.btnSave = new System.Windows.Forms.Button();
  34. this.btnClear = new System.Windows.Forms.Button();
  35. ((System.ComponentModel.ISupportInitialize)(this.dgvFile)).BeginInit();
  36. this.SuspendLayout();
  37. //
  38. // btnFile
  39. //
  40. this.btnFile.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  41. this.btnFile.Location = new System.Drawing.Point(289, 3);
  42. this.btnFile.Name = "btnFile";
  43. this.btnFile.Size = new System.Drawing.Size(97, 31);
  44. this.btnFile.TabIndex = 10;
  45. this.btnFile.Text = "....Choose File";
  46. this.btnFile.UseVisualStyleBackColor = true;
  47. this.btnFile.Click += new System.EventHandler(this.btnFile_Click);
  48. //
  49. // dgvFile
  50. //
  51. this.dgvFile.AllowUserToAddRows = false;
  52. this.dgvFile.AllowUserToDeleteRows = false;
  53. this.dgvFile.BackgroundColor = System.Drawing.SystemColors.Control;
  54. this.dgvFile.ColumnHeadersHeight = 28;
  55. this.dgvFile.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
  56. this.dgvFile.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
  57. this.fileName,
  58. this.filePath,
  59. this.fileSavePath});
  60. this.dgvFile.Location = new System.Drawing.Point(2, 39);
  61. this.dgvFile.Name = "dgvFile";
  62. this.dgvFile.ReadOnly = true;
  63. this.dgvFile.RowHeadersVisible = false;
  64. this.dgvFile.RowHeadersWidth = 30;
  65. this.dgvFile.Size = new System.Drawing.Size(693, 258);
  66. this.dgvFile.TabIndex = 1;
  67. //
  68. // fileName
  69. //
  70. this.fileName.DataPropertyName = "cname";
  71. this.fileName.HeaderText = "Name";
  72. this.fileName.Name = "fileName";
  73. this.fileName.ReadOnly = true;
  74. this.fileName.Width = 150;
  75. //
  76. // filePath
  77. //
  78. this.filePath.DataPropertyName = "cpath";
  79. this.filePath.HeaderText = "Path";
  80. this.filePath.Name = "filePath";
  81. this.filePath.ReadOnly = true;
  82. this.filePath.Width = 250;
  83. //
  84. // fileSavePath
  85. //
  86. this.fileSavePath.DataPropertyName = "csaveto";
  87. this.fileSavePath.HeaderText = "Save To";
  88. this.fileSavePath.Name = "fileSavePath";
  89. this.fileSavePath.ReadOnly = true;
  90. this.fileSavePath.Width = 300;
  91. //
  92. // btnSave
  93. //
  94. this.btnSave.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  95. this.btnSave.Location = new System.Drawing.Point(351, 304);
  96. this.btnSave.Name = "btnSave";
  97. this.btnSave.Size = new System.Drawing.Size(98, 32);
  98. this.btnSave.TabIndex = 9;
  99. this.btnSave.Text = "Save";
  100. this.btnSave.UseVisualStyleBackColor = true;
  101. this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
  102. //
  103. // btnClear
  104. //
  105. this.btnClear.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  106. this.btnClear.Location = new System.Drawing.Point(247, 304);
  107. this.btnClear.Name = "btnClear";
  108. this.btnClear.Size = new System.Drawing.Size(98, 32);
  109. this.btnClear.TabIndex = 10;
  110. this.btnClear.Text = "Clear";
  111. this.btnClear.UseVisualStyleBackColor = true;
  112. this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
  113. //
  114. // FileUpload
  115. //
  116. this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F);
  117. this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  118. this.BackColor = System.Drawing.SystemColors.Control;
  119. this.ClientSize = new System.Drawing.Size(697, 345);
  120. this.Controls.Add(this.btnFile);
  121. this.Controls.Add(this.btnClear);
  122. this.Controls.Add(this.btnSave);
  123. this.Controls.Add(this.dgvFile);
  124. this.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  125. this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
  126. this.MaximizeBox = false;
  127. this.Name = "FileUpload";
  128. this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
  129. this.Text = "File Upload";
  130. this.Load += new System.EventHandler(this.FileUpload_Load);
  131. ((System.ComponentModel.ISupportInitialize)(this.dgvFile)).EndInit();
  132. this.ResumeLayout(false);
  133. }
  134. #endregion
  135. private System.Windows.Forms.DataGridView dgvFile;
  136. private System.Windows.Forms.Button btnSave;
  137. private System.Windows.Forms.Button btnFile;
  138. private System.Windows.Forms.Button btnClear;
  139. private System.Windows.Forms.DataGridViewTextBoxColumn fileName;
  140. private System.Windows.Forms.DataGridViewTextBoxColumn filePath;
  141. private System.Windows.Forms.DataGridViewTextBoxColumn fileSavePath;
  142. }
  143. }
Then, we have to declare two variables. One is to where you want to save the file and another one is a data table where we store the uploaded file details.
  1. string strSavePath = @"D:\MyFolder\";
  2. DataTable dtData;
Now, on the page load event, initialize that data table by calling the "CreateTable" method.
  1. private void FileUpload_Load(object sender, EventArgs e)
  2. {
  3. dtData = CreateTable();
  4. }
  5. private DataTable CreateTable()
  6. {
  7. DataTable dtReturn = new DataTable();
  8. dtReturn.Columns.Add("cname", typeof(string));
  9. dtReturn.Columns.Add("cpath", typeof(string));
  10. dtReturn.Columns.Add("csaveto", typeof(string));
  11. return dtReturn;
  12. }
Here, we choose one file or multiple files to save to MyFolder.
  1. OpenFileDialog fdlg = new OpenFileDialog();
  2. fdlg.Title = "Select file";
  3. fdlg.InitialDirectory = Environment.SpecialFolder.Desktop.ToString();
  4. fdlg.Filter = string.Format("{0}{1}{2} ({3})|{3}", fdlg.Filter, "", "All Files", "*.*");
  5. // Code for image filter
  6. ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
  7. foreach (ImageCodecInfo c in codecs)
  8. {
  9. string codecName = c.CodecName.Substring(8).Replace("Codec", "Files").Trim();
  10. fdlg.Filter = string.Format("{0}{1}{2} ({3})|{3}", fdlg.Filter, "|", codecName, c.FilenameExtension);
  11. }
  12. // Code for files filter
  13. fdlg.Filter = fdlg.Filter + "|CSV Files (*.csv)|*.csv";
  14. fdlg.Filter = fdlg.Filter + "|Excel Files (.xls ,.xlsx)| *.xls ;*.xlsx";
  15. fdlg.Filter = fdlg.Filter + "|PDF Files (.pdf)|*.pdf";
  16. fdlg.Filter = fdlg.Filter + "|Text Files (*.txt)|*.txt";
  17. fdlg.Filter = fdlg.Filter + "|Word Files (.docx ,.doc)|*.docx;*.doc";
  18. fdlg.Filter = fdlg.Filter + "|XML Files (*.xml)|*.xml";
  19. fdlg.FilterIndex = 1;
  20. fdlg.RestoreDirectory = true;
  21. fdlg.Multiselect = true;
  22. if (fdlg.ShowDialog() == DialogResult.OK)
  23. {
  24. foreach (string file in fdlg.FileNames)
  25. {
  26. if (file != string.Empty)
  27. {
  28. DataRow drRow = dtData.NewRow();
  29. drRow["cname"] = Path.GetFileNameWithoutExtension(file);
  30. drRow["cpath"] = file;
  31. drRow["csaveto"] = strSavePath + RenameFile(file);
  32. dtData.Rows.Add(drRow);
  33. }
  34. }
  35. }
  36. dgvFile.DataSource = dtData;
Now, let us save them to a folder using File.Copy.
  1. File.Copy(oldPath, newPath, true);
Here is the complete code for FileUpload.cs file.
  1. using System;
  2. using System.IO;
  3. using System.Data;
  4. using System.Drawing.Imaging;
  5. using System.Windows.Forms;
  6. namespace FileUploads
  7. {
  8. public partial class FileUpload : Form
  9. {
  10. string strSavePath = @"D:\MyFolder\";
  11. DataTable dtData;
  12. public FileUpload()
  13. {
  14. InitializeComponent();
  15. }
  16. private void FileUpload_Load(object sender, EventArgs e)
  17. {
  18. dtData = CreateTable();
  19. }
  20. private DataTable CreateTable()
  21. {
  22. DataTable dtReturn = new DataTable();
  23. dtReturn.Columns.Add("cname", typeof(string));
  24. dtReturn.Columns.Add("cpath", typeof(string));
  25. dtReturn.Columns.Add("csaveto", typeof(string));
  26. return dtReturn;
  27. }
  28. private void btnSave_Click(object sender, EventArgs e)
  29. {
  30. if (dgvFile.Rows.Count > 0)
  31. {
  32. if (!Directory.Exists(strSavePath))
  33. {
  34. Directory.CreateDirectory(strSavePath);
  35. }
  36. int numRes = 0;
  37. for (int i = 0; i < dgvFile.Rows.Count; i++)
  38. {
  39. try
  40. {
  41. string oldPath = dgvFile.Rows[i].Cells["filePath"].Value.ToString();
  42. string fileSavePath = dgvFile.Rows[i].Cells["fileSavePath"].Value.ToString();
  43. File.Copy(oldPath, fileSavePath, true);
  44. numRes++;
  45. }
  46. catch { }
  47. }
  48. MessageBox.Show(numRes.ToString() + " nos of file saved !");
  49. dtData.Rows.Clear();
  50. dgvFile.DataSource = dtData;
  51. }
  52. }
  53. private void btnClear_Click(object sender, EventArgs e)
  54. {
  55. dtData.Rows.Clear();
  56. dgvFile.DataSource = dtData;
  57. }
  58. private void btnFile_Click(object sender, EventArgs e)
  59. {
  60. OpenFileDialog fdlg = new OpenFileDialog();
  61. fdlg.Title = "Select file";
  62. fdlg.InitialDirectory = Environment.SpecialFolder.Desktop.ToString();
  63. fdlg.Filter = string.Format("{0}{1}{2} ({3})|{3}", fdlg.Filter, "", "All Files", "*.*");
  64. // Code for image filter
  65. ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
  66. foreach (ImageCodecInfo c in codecs)
  67. {
  68. string codecName = c.CodecName.Substring(8).Replace("Codec", "Files").Trim();
  69. fdlg.Filter = string.Format("{0}{1}{2} ({3})|{3}", fdlg.Filter, "|", codecName, c.FilenameExtension);
  70. }
  71. // Code for files filter
  72. fdlg.Filter = fdlg.Filter + "|CSV Files (*.csv)|*.csv";
  73. fdlg.Filter = fdlg.Filter + "|Excel Files (.xls ,.xlsx)| *.xls ;*.xlsx";
  74. fdlg.Filter = fdlg.Filter + "|PDF Files (.pdf)|*.pdf";
  75. fdlg.Filter = fdlg.Filter + "|Text Files (*.txt)|*.txt";
  76. fdlg.Filter = fdlg.Filter + "|Word Files (.docx ,.doc)|*.docx;*.doc";
  77. fdlg.Filter = fdlg.Filter + "|XML Files (*.xml)|*.xml";
  78. fdlg.FilterIndex = 1;
  79. fdlg.RestoreDirectory = true;
  80. fdlg.Multiselect = true;
  81. if (fdlg.ShowDialog() == DialogResult.OK)
  82. {
  83. foreach (string file in fdlg.FileNames)
  84. {
  85. if (file != string.Empty)
  86. {
  87. DataRow drRow = dtData.NewRow();
  88. drRow["cname"] = Path.GetFileNameWithoutExtension(file);
  89. drRow["cpath"] = file;
  90. drRow["csaveto"] = strSavePath + RenameFile(file);
  91. dtData.Rows.Add(drRow);
  92. }
  93. }
  94. }
  95. dgvFile.DataSource = dtData;
  96. }
  97. public string RenameFile(string filePath)
  98. {
  99. string strExt = Path.GetExtension(filePath);
  100. string fileName = Guid.NewGuid().ToString("N") + strExt;
  101. return fileName;
  102. }
  103. }
  104. }
If you want to upload files from URL, then you can use WebClient.
  1. WebClient webClient = new WebClient();
  2. webClient.DownloadFileAsync(new Uri(oldPath), newPath);
Before that, you have to check if the given URL exists or not. For this, just call the URLExists method.
  1. public bool URLExists(string url)
  2. {
  3. bool result = true;
  4. try
  5. {
  6. WebRequest webRequest = WebRequest.Create(url);
  7. webRequest.Timeout = 1200; // miliseconds
  8. webRequest.Method = "HEAD";
  9. webRequest.GetResponse();
  10. }
  11. catch
  12. {
  13. result = false;
  14. }
  15. return result;
  16. }
By using these easy methods, we can upload a file or multiple files to a specific folder.

These simple tips may help beginner level readers to understand the concepts of uploading files to a folder.

Hope this will help you.