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.
- namespace FileUploads
- {
- partial class FileUpload
- {
-
-
-
- private System.ComponentModel.IContainer components = null;
-
-
-
-
-
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
-
- #region Windows Form Designer generated code
-
-
-
-
-
- private void InitializeComponent()
- {
- this.btnFile = new System.Windows.Forms.Button();
- this.dgvFile = new System.Windows.Forms.DataGridView();
- this.fileName = new System.Windows.Forms.DataGridViewTextBoxColumn();
- this.filePath = new System.Windows.Forms.DataGridViewTextBoxColumn();
- this.fileSavePath = new System.Windows.Forms.DataGridViewTextBoxColumn();
- this.btnSave = new System.Windows.Forms.Button();
- this.btnClear = new System.Windows.Forms.Button();
- ((System.ComponentModel.ISupportInitialize)(this.dgvFile)).BeginInit();
- this.SuspendLayout();
-
-
-
- this.btnFile.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
- this.btnFile.Location = new System.Drawing.Point(289, 3);
- this.btnFile.Name = "btnFile";
- this.btnFile.Size = new System.Drawing.Size(97, 31);
- this.btnFile.TabIndex = 10;
- this.btnFile.Text = "....Choose File";
- this.btnFile.UseVisualStyleBackColor = true;
- this.btnFile.Click += new System.EventHandler(this.btnFile_Click);
-
-
-
- this.dgvFile.AllowUserToAddRows = false;
- this.dgvFile.AllowUserToDeleteRows = false;
- this.dgvFile.BackgroundColor = System.Drawing.SystemColors.Control;
- this.dgvFile.ColumnHeadersHeight = 28;
- this.dgvFile.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
- this.dgvFile.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
- this.fileName,
- this.filePath,
- this.fileSavePath});
- this.dgvFile.Location = new System.Drawing.Point(2, 39);
- this.dgvFile.Name = "dgvFile";
- this.dgvFile.ReadOnly = true;
- this.dgvFile.RowHeadersVisible = false;
- this.dgvFile.RowHeadersWidth = 30;
- this.dgvFile.Size = new System.Drawing.Size(693, 258);
- this.dgvFile.TabIndex = 1;
-
-
-
- this.fileName.DataPropertyName = "cname";
- this.fileName.HeaderText = "Name";
- this.fileName.Name = "fileName";
- this.fileName.ReadOnly = true;
- this.fileName.Width = 150;
-
-
-
- this.filePath.DataPropertyName = "cpath";
- this.filePath.HeaderText = "Path";
- this.filePath.Name = "filePath";
- this.filePath.ReadOnly = true;
- this.filePath.Width = 250;
-
-
-
- this.fileSavePath.DataPropertyName = "csaveto";
- this.fileSavePath.HeaderText = "Save To";
- this.fileSavePath.Name = "fileSavePath";
- this.fileSavePath.ReadOnly = true;
- this.fileSavePath.Width = 300;
-
-
-
- this.btnSave.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
- this.btnSave.Location = new System.Drawing.Point(351, 304);
- this.btnSave.Name = "btnSave";
- this.btnSave.Size = new System.Drawing.Size(98, 32);
- this.btnSave.TabIndex = 9;
- this.btnSave.Text = "Save";
- this.btnSave.UseVisualStyleBackColor = true;
- this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
-
-
-
- this.btnClear.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
- this.btnClear.Location = new System.Drawing.Point(247, 304);
- this.btnClear.Name = "btnClear";
- this.btnClear.Size = new System.Drawing.Size(98, 32);
- this.btnClear.TabIndex = 10;
- this.btnClear.Text = "Clear";
- this.btnClear.UseVisualStyleBackColor = true;
- this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
-
-
-
- this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F);
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.BackColor = System.Drawing.SystemColors.Control;
- this.ClientSize = new System.Drawing.Size(697, 345);
- this.Controls.Add(this.btnFile);
- this.Controls.Add(this.btnClear);
- this.Controls.Add(this.btnSave);
- this.Controls.Add(this.dgvFile);
- this.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
- this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
- this.MaximizeBox = false;
- this.Name = "FileUpload";
- this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
- this.Text = "File Upload";
- this.Load += new System.EventHandler(this.FileUpload_Load);
- ((System.ComponentModel.ISupportInitialize)(this.dgvFile)).EndInit();
- this.ResumeLayout(false);
-
- }
-
- #endregion
- private System.Windows.Forms.DataGridView dgvFile;
- private System.Windows.Forms.Button btnSave;
- private System.Windows.Forms.Button btnFile;
- private System.Windows.Forms.Button btnClear;
- private System.Windows.Forms.DataGridViewTextBoxColumn fileName;
- private System.Windows.Forms.DataGridViewTextBoxColumn filePath;
- private System.Windows.Forms.DataGridViewTextBoxColumn fileSavePath;
- }
- }
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.
- string strSavePath = @"D:\MyFolder\";
- DataTable dtData;
Now, on the page load event, initialize that data table by calling the "CreateTable" method.
- private void FileUpload_Load(object sender, EventArgs e)
- {
- dtData = CreateTable();
- }
-
- private DataTable CreateTable()
- {
- DataTable dtReturn = new DataTable();
- dtReturn.Columns.Add("cname", typeof(string));
- dtReturn.Columns.Add("cpath", typeof(string));
- dtReturn.Columns.Add("csaveto", typeof(string));
- return dtReturn;
- }
Here, we choose one file or multiple files to save to MyFolder.
- OpenFileDialog fdlg = new OpenFileDialog();
- fdlg.Title = "Select file";
- fdlg.InitialDirectory = Environment.SpecialFolder.Desktop.ToString();
- fdlg.Filter = string.Format("{0}{1}{2} ({3})|{3}", fdlg.Filter, "", "All Files", "*.*");
-
- ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
- foreach (ImageCodecInfo c in codecs)
- {
- string codecName = c.CodecName.Substring(8).Replace("Codec", "Files").Trim();
- fdlg.Filter = string.Format("{0}{1}{2} ({3})|{3}", fdlg.Filter, "|", codecName, c.FilenameExtension);
- }
-
- fdlg.Filter = fdlg.Filter + "|CSV Files (*.csv)|*.csv";
- fdlg.Filter = fdlg.Filter + "|Excel Files (.xls ,.xlsx)| *.xls ;*.xlsx";
- fdlg.Filter = fdlg.Filter + "|PDF Files (.pdf)|*.pdf";
- fdlg.Filter = fdlg.Filter + "|Text Files (*.txt)|*.txt";
- fdlg.Filter = fdlg.Filter + "|Word Files (.docx ,.doc)|*.docx;*.doc";
- fdlg.Filter = fdlg.Filter + "|XML Files (*.xml)|*.xml";
-
- fdlg.FilterIndex = 1;
- fdlg.RestoreDirectory = true;
- fdlg.Multiselect = true;
- if (fdlg.ShowDialog() == DialogResult.OK)
- {
- foreach (string file in fdlg.FileNames)
- {
- if (file != string.Empty)
- {
- DataRow drRow = dtData.NewRow();
- drRow["cname"] = Path.GetFileNameWithoutExtension(file);
- drRow["cpath"] = file;
- drRow["csaveto"] = strSavePath + RenameFile(file);
- dtData.Rows.Add(drRow);
- }
- }
- }
- dgvFile.DataSource = dtData;
Now, let us save them to a folder using File.Copy.
- File.Copy(oldPath, newPath, true);
Here is the complete code for FileUpload.cs file.
- using System;
- using System.IO;
- using System.Data;
- using System.Drawing.Imaging;
- using System.Windows.Forms;
-
- namespace FileUploads
- {
- public partial class FileUpload : Form
- {
- string strSavePath = @"D:\MyFolder\";
- DataTable dtData;
-
- public FileUpload()
- {
- InitializeComponent();
- }
-
- private void FileUpload_Load(object sender, EventArgs e)
- {
- dtData = CreateTable();
- }
-
- private DataTable CreateTable()
- {
- DataTable dtReturn = new DataTable();
- dtReturn.Columns.Add("cname", typeof(string));
- dtReturn.Columns.Add("cpath", typeof(string));
- dtReturn.Columns.Add("csaveto", typeof(string));
- return dtReturn;
- }
-
- private void btnSave_Click(object sender, EventArgs e)
- {
- if (dgvFile.Rows.Count > 0)
- {
- if (!Directory.Exists(strSavePath))
- {
- Directory.CreateDirectory(strSavePath);
- }
- int numRes = 0;
- for (int i = 0; i < dgvFile.Rows.Count; i++)
- {
- try
- {
- string oldPath = dgvFile.Rows[i].Cells["filePath"].Value.ToString();
- string fileSavePath = dgvFile.Rows[i].Cells["fileSavePath"].Value.ToString();
- File.Copy(oldPath, fileSavePath, true);
- numRes++;
- }
- catch { }
- }
- MessageBox.Show(numRes.ToString() + " nos of file saved !");
- dtData.Rows.Clear();
- dgvFile.DataSource = dtData;
- }
- }
-
- private void btnClear_Click(object sender, EventArgs e)
- {
- dtData.Rows.Clear();
- dgvFile.DataSource = dtData;
- }
-
- private void btnFile_Click(object sender, EventArgs e)
- {
- OpenFileDialog fdlg = new OpenFileDialog();
- fdlg.Title = "Select file";
- fdlg.InitialDirectory = Environment.SpecialFolder.Desktop.ToString();
- fdlg.Filter = string.Format("{0}{1}{2} ({3})|{3}", fdlg.Filter, "", "All Files", "*.*");
-
- ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
- foreach (ImageCodecInfo c in codecs)
- {
- string codecName = c.CodecName.Substring(8).Replace("Codec", "Files").Trim();
- fdlg.Filter = string.Format("{0}{1}{2} ({3})|{3}", fdlg.Filter, "|", codecName, c.FilenameExtension);
- }
-
- fdlg.Filter = fdlg.Filter + "|CSV Files (*.csv)|*.csv";
- fdlg.Filter = fdlg.Filter + "|Excel Files (.xls ,.xlsx)| *.xls ;*.xlsx";
- fdlg.Filter = fdlg.Filter + "|PDF Files (.pdf)|*.pdf";
- fdlg.Filter = fdlg.Filter + "|Text Files (*.txt)|*.txt";
- fdlg.Filter = fdlg.Filter + "|Word Files (.docx ,.doc)|*.docx;*.doc";
- fdlg.Filter = fdlg.Filter + "|XML Files (*.xml)|*.xml";
-
- fdlg.FilterIndex = 1;
- fdlg.RestoreDirectory = true;
- fdlg.Multiselect = true;
- if (fdlg.ShowDialog() == DialogResult.OK)
- {
- foreach (string file in fdlg.FileNames)
- {
- if (file != string.Empty)
- {
- DataRow drRow = dtData.NewRow();
- drRow["cname"] = Path.GetFileNameWithoutExtension(file);
- drRow["cpath"] = file;
- drRow["csaveto"] = strSavePath + RenameFile(file);
- dtData.Rows.Add(drRow);
- }
- }
- }
- dgvFile.DataSource = dtData;
- }
-
- public string RenameFile(string filePath)
- {
- string strExt = Path.GetExtension(filePath);
- string fileName = Guid.NewGuid().ToString("N") + strExt;
- return fileName;
- }
- }
- }
If you want to upload files from URL, then you can use WebClient.
- WebClient webClient = new WebClient();
- 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.
- public bool URLExists(string url)
- {
- bool result = true;
- try
- {
- WebRequest webRequest = WebRequest.Create(url);
- webRequest.Timeout = 1200;
- webRequest.Method = "HEAD";
- webRequest.GetResponse();
- }
- catch
- {
- result = false;
- }
- 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.