How to upload files to a folder using C# code

How to upload files to a folder using Csharp code

Introduction

In this article, you’ll understand how to upload files to the folder using the c# code. and step by step we’ll create a Microsoft ASP.NET file (WebForm1.aspx) and its related code-behind file (WebForm1.aspx.cs) to file uploads.

Create an ASP.NET application

Let’s go to Visual Studio, follow these steps to create a new application to upload files using c#:

  1. Open Visual Studio.
  2. Select File menu, point to New and then click on Project.
  3. In the New Project dialog box, click Visual C# Projects under Project Types, and then click ASP.NET Web Application under Templates.

In the dialog Location box, type the URL to create the project. For this example, type
http://localhost/FileUpload, which creates the default project name of FileUpload. Notice that the FileUpload.aspx file loads in the Designer view of Visual Studio .NET.

First, we have to create a WinForm like in the given code. Here is the code for FileUpload.Designer.cs file.

namespace FileUploads  
{  
    partial class FileUpload  
    {  
        /// <summary>  
        /// Required designer variable.  
        /// </summary>  
        private System.ComponentModel.IContainer components = null;  
  
        /// <summary>  
        /// Clean up any resources being used.  
        /// </summary>  
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>  
        protected override void Dispose(bool disposing)  
        {  
            if (disposing && (components != null))  
            {  
                components.Dispose();  
            }  
            base.Dispose(disposing);  
        }  
 
        #region Windows Form Designer generated code  
  
        /// <summary>  
        /// Required method for Designer support - do not modify  
        /// the contents of this method with the code editor.  
        /// </summary>  
        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();  
            //   
            // btnFile  
            //   
            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);  
            //   
            // dgvFile  
            //   
            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;  
            //   
            // fileName  
            //   
            this.fileName.DataPropertyName = "cname";  
            this.fileName.HeaderText = "Name";  
            this.fileName.Name = "fileName";  
            this.fileName.ReadOnly = true;  
            this.fileName.Width = 150;  
            //   
            // filePath  
            //   
            this.filePath.DataPropertyName = "cpath";  
            this.filePath.HeaderText = "Path";  
            this.filePath.Name = "filePath";  
            this.filePath.ReadOnly = true;  
            this.filePath.Width = 250;  
            //   
            // fileSavePath  
            //   
            this.fileSavePath.DataPropertyName = "csaveto";  
            this.fileSavePath.HeaderText = "Save To";  
            this.fileSavePath.Name = "fileSavePath";  
            this.fileSavePath.ReadOnly = true;  
            this.fileSavePath.Width = 300;  
            //   
            // btnSave  
            //   
            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);  
            //   
            // btnClear  
            //   
            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);  
            //   
            // FileUpload  
            //   
            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. after that, 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", "*.*");  
// Code for image filter  
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);  
}  
// Code for files filter  
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", "*.*");  
            // Code for image filter  
            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);  
            }  
            // Code for files filter  
            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; // miliseconds  
        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.

2 Comments

  1. It’s actually a great and useful piece of info. I am glad that you simply shared this useful information with us. Please keep us up to date like this. Thanks for sharing.|

  2. Great article! This is the type of information that should be shared across the internet. Disgrace on the seek engines for now not positioning this submit higher! Come on over and consult with my web site . Thank you =)|

Leave a Reply

Your email address will not be published. Required fields are marked *