FTP Uploader

In this post we are going to see how to upload a file using FTP in Windows Form application. In our previous post we have install and configure FTP Server on IIS 10. Now we are going to create a sample application to connect the FTP server including below operations:

  • List FTP Server Directory Files
  • Create Directory
  • Check Existing Directory
  • Upload Files to FTP Server Directory
  • Delete File from FTP Server

Please overview previous post if you are new to FTP Server configuration: https://shashangka.com/2019/02/08/install-configure-ftp-server-on-iis-10


List FTP Server Directory Files:

List getDirectoryFiles()
{
    FtpWebRequest ftpRequest = null;
    List resultlistFile = null;
    try
    {
        strHostName = txtHost.Text.Trim();
        strUserName = txtusername.Text.Trim();
        strPassword = txtPassword.Text.Trim();
        strPort = txtPort.Text.Trim();

        if ((strHostName != string.Empty) && (strUserName != string.Empty) && (strPassword != string.Empty))
        {
            //FTP Request
            string _strHostName = strHostName + "/" + strHostdest;
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(_strHostName);
            ftpRequest.Credentials = new NetworkCredential(strUserName, strPassword);
            ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
            ftpRequest.UseBinary = true;
            ftpRequest.KeepAlive = false;
            ftpRequest.UsePassive = true;
            ftpRequest.Timeout = Int32.MaxValue;
            ftpRequest.ReadWriteTimeout = Int32.MaxValue;
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

            //Read Directory
            string[] listFile = null;
            using (StreamReader reader = new StreamReader(ftpResponse.GetResponseStream()))
            {
                string strFiles = reader.ReadToEnd();
                listFile = strFiles.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            }

            if (listFile.Length > 0)
            {
                resultlistFile = new List();
                int i = 0;
                foreach (string file in listFile)
                {
                    i++;

                    //GET FileInformation
                    string filename = file;
                    filename = filename.Remove(0, 24); filename = filename.Trim();
                    string[] fileinfo = filename.Split(' ');
                    if (fileinfo.Length > 2)
                    {
                        string _filename = string.Empty;
                        for (int j = 1; j < fileinfo.Length; j++) { _filename += fileinfo[j] + ' '; }
                        filename = _filename;
                    }
                    else
                    {
                        filename = fileinfo[1];
                    }

                    string filesize = ToFileSize(Convert.ToDouble(fileinfo[0]));
                    string date = file.Substring(0, 17);

                    //SET FileInformation
                    Fileinfo item = new Fileinfo()
                    {
                        Id = i,
                        DateCreated = DateTime.Parse(date),
                        Filename = filename,
                        Filesize = filesize
                    };

                    resultlistFile.Add(item);
                }
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Connection Error!!", "Message");
        ex.ToString();
    }
    finally
    {
        if (ftpRequest != null)
        {
            ftpRequest = null;
        }

        if (ftpResponse != null)
        {
            ftpResponse.Close();
        }
    }
    return resultlistFile;
}

Upload Files to FTP Server Directory:

void FtpUploadFile(Fileinfo file)
{
    FtpWebRequest ftpRequest = null;
    FileStream filestream = null;
    Stream stream = null;
    try
    {
        currentPosition = 0; totalTransfered = 0; size = 0; transferRate = 0;
        FileInfo fileInfo = new FileInfo(file.Filesource);
        size = fileInfo.Length;
        progbarFtp.Minimum = 0;
        progbarFtp.Maximum = 100;
        long currentSize = 0;
        long incrementSize = (size / 100);

        string _strHostName = strHostName + "/" + file.Filedestination;
        filestream = new FileStream(file.Filesource, FileMode.Open, FileAccess.Read);
        ftpRequest = FtpWebRequest.Create(_strHostName) as FtpWebRequest;
        ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
        ftpRequest.Credentials = new NetworkCredential(strUserName, strPassword);
        ftpRequest.UseBinary = true;
        ftpRequest.KeepAlive = false;
        ftpRequest.UsePassive = true;
        ftpRequest.Timeout = Int32.MaxValue;
        ftpRequest.ReadWriteTimeout = Int32.MaxValue;
        stream = ftpRequest.GetRequestStream();

        const int bufferLength = (1 * 1024);
        byte[] buffer = new byte[bufferLength];
        int read = 0;
        while ((read = filestream.Read(buffer, 0, buffer.Length)) != 0)
        {
            stream.Write(buffer, 0, read);
            currentSize += read;
            totalTransfered += read;
            transferRate = read;
            if (currentSize >= incrementSize)
            {
                currentSize -= incrementSize;
                progbarFtp.Invoke(new updatebar(this.UpdateProgress));
            }
        }
        stream.Flush();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Connection Error!!", "Message");
        ex.ToString();
    }
    finally
    {
        if (filestream != null)
        {
            filestream.Close();
            filestream.Dispose();
        }

        if (stream != null)
        {
            stream.Close();
            stream.Dispose();
        }

        if (ftpRequest != null)
        {
            ftpRequest = null;
        }

        if (ftpResponse != null)
        {
            ftpResponse.Close();
        }
    }
}

Create Directory:

void createDirectory()
{
    FtpWebRequest ftpRequest = null;
    try
    {
        string _strHostName = strHostName + "/" + strHostdest;
        ftpRequest = (FtpWebRequest)WebRequest.Create(_strHostName);
        ftpRequest.Credentials = new NetworkCredential(strUserName, strPassword);
        ftpRequest.UseBinary = true;
        ftpRequest.KeepAlive = false;
        ftpRequest.UsePassive = true;
        ftpRequest.Timeout = Int32.MaxValue;
        ftpRequest.ReadWriteTimeout = Int32.MaxValue;
        ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Connection Error!!", "Message");
        ex.ToString();
    }
    finally
    {
        if (ftpRequest != null)
        {
            ftpRequest = null;
        }

        if (ftpResponse != null)
        {
            ftpResponse.Close();
        }
    }
}

Check Existing Directory:

bool isDirectoryExist()
{
    FtpWebRequest ftpRequest = null;
    try
    {
        string _strHostName = strHostName + "/" + strHostdest;
        ftpRequest = (FtpWebRequest)WebRequest.Create(_strHostName);
        ftpRequest.Credentials = new NetworkCredential(strUserName, strPassword);
        ftpRequest.UseBinary = true;
        ftpRequest.KeepAlive = false;
        ftpRequest.UsePassive = true;
        ftpRequest.Timeout = Int32.MaxValue;
        ftpRequest.ReadWriteTimeout = Int32.MaxValue;
        ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        return true;
    }
    catch (WebException ex)
    {
        ex.ToString();
        return false;
    }
    finally
    {
        if (ftpRequest != null)
        {
            ftpRequest = null;
        }

        if (ftpResponse != null)
        {
            ftpResponse.Close();
        }
    }
}

Delete File from FTP Server:

void deleteFile()
{
    FtpWebRequest ftpRequest = null;
    try
    {
        string _strHostName = strHostName + "/" + strHostdest + "/" + SelectedFile;
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(_strHostName);
        ftpRequest.Credentials = new NetworkCredential(strUserName, strPassword);
        ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
        ftpRequest.UsePassive = true;
        ftpRequest.UseBinary = true;
        ftpRequest.KeepAlive = false;
        ftpRequest.Timeout = Int32.MaxValue;
        ftpRequest.ReadWriteTimeout = Int32.MaxValue;
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

        fillGrid();
        SelectedFile = string.Empty;
        btnCancel.Text = "Cancel";
    }
    catch (Exception ex)
    {
        MessageBox.Show("Connection Error!!", "Message");
        ex.ToString();
    }
    finally
    {
        if (ftpRequest != null)
        {
            ftpRequest = null;
        }

        if (ftpResponse != null)
        {
            ftpResponse.Close();
        }
    }
}

Download/clone full source code from , Thanks 🙂

References:

  • https://www.codeproject.com/Tips/443588/Simple-Csharp-FTP-Class

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

One thought on “FTP Uploader”

  • I was suggested this web site by means of my cousin. I
    am now not positive whether or not this post is written by way of him as
    nobody else recognize such specific about my problem.
    You are wonderful! Thanks!

Leave a Reply