Upload Files To Folder Using C#

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.   
  10.         /// <summary>  
  11.         /// Clean up any resources being used.  
  12.         /// </summary>  
  13.         /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>  
  14.         protected override void Dispose(bool disposing)  
  15.         {  
  16.             if (disposing && (components != null))  
  17.             {  
  18.                 components.Dispose();  
  19.             }  
  20.             base.Dispose(disposing);  
  21.         }  
  22.  
  23.         #region Windows Form Designer generated code  
  24.   
  25.         /// <summary>  
  26.         /// Required method for Designer support - do not modify  
  27.         /// the contents of this method with the code editor.  
  28.         /// </summary>  
  29.         private void InitializeComponent()  
  30.         {  
  31.             this.btnFile = new System.Windows.Forms.Button();  
  32.             this.dgvFile = new System.Windows.Forms.DataGridView();  
  33.             this.fileName = new System.Windows.Forms.DataGridViewTextBoxColumn();  
  34.             this.filePath = new System.Windows.Forms.DataGridViewTextBoxColumn();  
  35.             this.fileSavePath = new System.Windows.Forms.DataGridViewTextBoxColumn();  
  36.             this.btnSave = new System.Windows.Forms.Button();  
  37.             this.btnClear = new System.Windows.Forms.Button();  
  38.             ((System.ComponentModel.ISupportInitialize)(this.dgvFile)).BeginInit();  
  39.             this.SuspendLayout();  
  40.             //   
  41.             // btnFile  
  42.             //   
  43.             this.btnFile.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));  
  44.             this.btnFile.Location = new System.Drawing.Point(289, 3);  
  45.             this.btnFile.Name = "btnFile";  
  46.             this.btnFile.Size = new System.Drawing.Size(97, 31);  
  47.             this.btnFile.TabIndex = 10;  
  48.             this.btnFile.Text = "....Choose File";  
  49.             this.btnFile.UseVisualStyleBackColor = true;  
  50.             this.btnFile.Click += new System.EventHandler(this.btnFile_Click);  
  51.             //   
  52.             // dgvFile  
  53.             //   
  54.             this.dgvFile.AllowUserToAddRows = false;  
  55.             this.dgvFile.AllowUserToDeleteRows = false;  
  56.             this.dgvFile.BackgroundColor = System.Drawing.SystemColors.Control;  
  57.             this.dgvFile.ColumnHeadersHeight = 28;  
  58.             this.dgvFile.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;  
  59.             this.dgvFile.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {  
  60.             this.fileName,  
  61.             this.filePath,  
  62.             this.fileSavePath});  
  63.             this.dgvFile.Location = new System.Drawing.Point(2, 39);  
  64.             this.dgvFile.Name = "dgvFile";  
  65.             this.dgvFile.ReadOnly = true;  
  66.             this.dgvFile.RowHeadersVisible = false;  
  67.             this.dgvFile.RowHeadersWidth = 30;  
  68.             this.dgvFile.Size = new System.Drawing.Size(693, 258);  
  69.             this.dgvFile.TabIndex = 1;  
  70.             //   
  71.             // fileName  
  72.             //   
  73.             this.fileName.DataPropertyName = "cname";  
  74.             this.fileName.HeaderText = "Name";  
  75.             this.fileName.Name = "fileName";  
  76.             this.fileName.ReadOnly = true;  
  77.             this.fileName.Width = 150;  
  78.             //   
  79.             // filePath  
  80.             //   
  81.             this.filePath.DataPropertyName = "cpath";  
  82.             this.filePath.HeaderText = "Path";  
  83.             this.filePath.Name = "filePath";  
  84.             this.filePath.ReadOnly = true;  
  85.             this.filePath.Width = 250;  
  86.             //   
  87.             // fileSavePath  
  88.             //   
  89.             this.fileSavePath.DataPropertyName = "csaveto";  
  90.             this.fileSavePath.HeaderText = "Save To";  
  91.             this.fileSavePath.Name = "fileSavePath";  
  92.             this.fileSavePath.ReadOnly = true;  
  93.             this.fileSavePath.Width = 300;  
  94.             //   
  95.             // btnSave  
  96.             //   
  97.             this.btnSave.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));  
  98.             this.btnSave.Location = new System.Drawing.Point(351, 304);  
  99.             this.btnSave.Name = "btnSave";  
  100.             this.btnSave.Size = new System.Drawing.Size(98, 32);  
  101.             this.btnSave.TabIndex = 9;  
  102.             this.btnSave.Text = "Save";  
  103.             this.btnSave.UseVisualStyleBackColor = true;  
  104.             this.btnSave.Click += new System.EventHandler(this.btnSave_Click);  
  105.             //   
  106.             // btnClear  
  107.             //   
  108.             this.btnClear.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));  
  109.             this.btnClear.Location = new System.Drawing.Point(247, 304);  
  110.             this.btnClear.Name = "btnClear";  
  111.             this.btnClear.Size = new System.Drawing.Size(98, 32);  
  112.             this.btnClear.TabIndex = 10;  
  113.             this.btnClear.Text = "Clear";  
  114.             this.btnClear.UseVisualStyleBackColor = true;  
  115.             this.btnClear.Click += new System.EventHandler(this.btnClear_Click);  
  116.             //   
  117.             // FileUpload  
  118.             //   
  119.             this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F);  
  120.             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;  
  121.             this.BackColor = System.Drawing.SystemColors.Control;  
  122.             this.ClientSize = new System.Drawing.Size(697, 345);  
  123.             this.Controls.Add(this.btnFile);  
  124.             this.Controls.Add(this.btnClear);  
  125.             this.Controls.Add(this.btnSave);  
  126.             this.Controls.Add(this.dgvFile);  
  127.             this.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));  
  128.             this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);  
  129.             this.MaximizeBox = false;  
  130.             this.Name = "FileUpload";  
  131.             this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;  
  132.             this.Text = "File Upload";  
  133.             this.Load += new System.EventHandler(this.FileUpload_Load);  
  134.             ((System.ComponentModel.ISupportInitialize)(this.dgvFile)).EndInit();  
  135.             this.ResumeLayout(false);  
  136.   
  137.         }  
  138.  
  139.         #endregion  
  140.         private System.Windows.Forms.DataGridView dgvFile;  
  141.         private System.Windows.Forms.Button btnSave;  
  142.         private System.Windows.Forms.Button btnFile;  
  143.         private System.Windows.Forms.Button btnClear;  
  144.         private System.Windows.Forms.DataGridViewTextBoxColumn fileName;  
  145.         private System.Windows.Forms.DataGridViewTextBoxColumn filePath;  
  146.         private System.Windows.Forms.DataGridViewTextBoxColumn fileSavePath;  
  147.     }  

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.   
  6. private DataTable CreateTable()  
  7. {  
  8.     DataTable dtReturn = new DataTable();  
  9.     dtReturn.Columns.Add("cname"typeof(string));  
  10.     dtReturn.Columns.Add("cpath"typeof(string));  
  11.     dtReturn.Columns.Add("csaveto"typeof(string));  
  12.     return dtReturn;  

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.   
  20. fdlg.FilterIndex = 1;  
  21. fdlg.RestoreDirectory = true;  
  22. fdlg.Multiselect = true;  
  23. if (fdlg.ShowDialog() == DialogResult.OK)  
  24. {  
  25.     foreach (string file in fdlg.FileNames)  
  26.     {  
  27.         if (file != string.Empty)  
  28.         {  
  29.             DataRow drRow = dtData.NewRow();  
  30.             drRow["cname"] = Path.GetFileNameWithoutExtension(file);  
  31.             drRow["cpath"] = file;  
  32.             drRow["csaveto"] = strSavePath + RenameFile(file);  
  33.             dtData.Rows.Add(drRow);  
  34.         }  
  35.     }  
  36. }  
  37. 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.   
  7. namespace FileUploads  
  8. {  
  9.     public partial class FileUpload : Form  
  10.     {  
  11.         string strSavePath = @"D:\MyFolder\";  
  12.         DataTable dtData;  
  13.   
  14.         public FileUpload()  
  15.         {  
  16.             InitializeComponent();  
  17.         }  
  18.           
  19.         private void FileUpload_Load(object sender, EventArgs e)  
  20.         {  
  21.             dtData = CreateTable();  
  22.         }  
  23.   
  24.         private DataTable CreateTable()  
  25.         {  
  26.             DataTable dtReturn = new DataTable();  
  27.             dtReturn.Columns.Add("cname"typeof(string));  
  28.             dtReturn.Columns.Add("cpath"typeof(string));  
  29.             dtReturn.Columns.Add("csaveto"typeof(string));  
  30.             return dtReturn;  
  31.         }  
  32.           
  33.         private void btnSave_Click(object sender, EventArgs e)  
  34.         {  
  35.             if (dgvFile.Rows.Count > 0)  
  36.             {  
  37.                 if (!Directory.Exists(strSavePath))  
  38.                 {  
  39.                     Directory.CreateDirectory(strSavePath);  
  40.                 }  
  41.                 int numRes = 0;              
  42.                 for (int i = 0; i < dgvFile.Rows.Count; i++)  
  43.                 {  
  44.                     try  
  45.                     {  
  46.                         string oldPath = dgvFile.Rows[i].Cells["filePath"].Value.ToString();  
  47.                         string fileSavePath = dgvFile.Rows[i].Cells["fileSavePath"].Value.ToString();  
  48.                         File.Copy(oldPath, fileSavePath, true);  
  49.                         numRes++;  
  50.                     }  
  51.                     catch { }  
  52.                 }  
  53.                 MessageBox.Show(numRes.ToString() + " nos of file saved !");  
  54.                 dtData.Rows.Clear();  
  55.                 dgvFile.DataSource = dtData;  
  56.             }  
  57.         }  
  58.   
  59.         private void btnClear_Click(object sender, EventArgs e)  
  60.         {  
  61.             dtData.Rows.Clear();  
  62.             dgvFile.DataSource = dtData;  
  63.         }  
  64.           
  65.         private void btnFile_Click(object sender, EventArgs e)  
  66.         {  
  67.             OpenFileDialog fdlg = new OpenFileDialog();  
  68.             fdlg.Title = "Select file";  
  69.             fdlg.InitialDirectory = Environment.SpecialFolder.Desktop.ToString();          
  70.             fdlg.Filter = string.Format("{0}{1}{2} ({3})|{3}", fdlg.Filter, """All Files""*.*");  
  71.             // Code for image filter  
  72.             ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();  
  73.             foreach (ImageCodecInfo c in codecs)  
  74.             {  
  75.                 string codecName = c.CodecName.Substring(8).Replace("Codec""Files").Trim();  
  76.                 fdlg.Filter = string.Format("{0}{1}{2} ({3})|{3}", fdlg.Filter, "|", codecName, c.FilenameExtension);  
  77.             }  
  78.             // Code for files filter  
  79.             fdlg.Filter = fdlg.Filter + "|CSV Files (*.csv)|*.csv";  
  80.             fdlg.Filter = fdlg.Filter + "|Excel Files (.xls ,.xlsx)|  *.xls ;*.xlsx";  
  81.             fdlg.Filter = fdlg.Filter + "|PDF Files (.pdf)|*.pdf";  
  82.             fdlg.Filter = fdlg.Filter + "|Text Files (*.txt)|*.txt";  
  83.             fdlg.Filter = fdlg.Filter + "|Word Files (.docx ,.doc)|*.docx;*.doc";  
  84.             fdlg.Filter = fdlg.Filter + "|XML Files (*.xml)|*.xml";  
  85.   
  86.             fdlg.FilterIndex = 1;  
  87.             fdlg.RestoreDirectory = true;  
  88.             fdlg.Multiselect = true;  
  89.             if (fdlg.ShowDialog() == DialogResult.OK)  
  90.             {  
  91.                 foreach (string file in fdlg.FileNames)  
  92.                 {  
  93.                     if (file != string.Empty)  
  94.                     {  
  95.                         DataRow drRow = dtData.NewRow();  
  96.                         drRow["cname"] = Path.GetFileNameWithoutExtension(file);  
  97.                         drRow["cpath"] = file;  
  98.                         drRow["csaveto"] = strSavePath + RenameFile(file);  
  99.                         dtData.Rows.Add(drRow);  
  100.                     }  
  101.                 }  
  102.             }  
  103.             dgvFile.DataSource = dtData;  
  104.         }  
  105.   
  106.         public string RenameFile(string filePath)  
  107.         {  
  108.             string strExt = Path.GetExtension(filePath);  
  109.             string fileName = Guid.NewGuid().ToString("N") + strExt;  
  110.             return fileName;  
  111.         }  
  112.     }  

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;  

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.