C# Tutorial – How to Upload files with FTP/ fileupload to server | FoxLearn

C# Tutorial – How to Upload files with FTP/ fileupload to server | FoxLearn


Welcome to the FoxLearn Today we will learn how to upload files with FTP First, We will design a simple UI allows you to enter the server name, username, password, and then select a file to upload to an FTP server The BackgroundWorker class allows you to run an operation on a separate, dedicated thread Time-consuming operations like downloads and database transactions can cause your user interface to seem as though it has stopped responding while they are running When you want a responsive UI and you are faced with long delays associated with such operations the BackgroundWorker class provides a convenient solution To set up for a background operation, add an event handler for the DoWork event Call your time-consuming operation in this event handler To start the operation, call RunWorkerAsync To receive notifications of progress updates, handle the ProgressChanged event To receive a notification when the operation is completed, handle the RunWorkerCompleted event The FtpWebRequest class enables you to programmatically create FTP connections to FTP Servers and transfer files To play the demo, you need to create an FTP account Thank you for watching this video

About the author

Comments

  1. somehow its not working :/ typed exactly the same as you did… could you also please send me the source:
    email : [email protected]
    would be really nice… ill continue finding an own solution till then 😀

  2. Hello, your video is very interesting, I tried to follow the steps shown, but then when I enter the data to upload the files to the server nothing happens, I already checked if the data is correct and apparently it is. Could you help me? Thank you

  3. hi,
    may i know how to upload any type of files into the sql database and also store it in an upload folder simultaneously…???

  4. Hello, Do you have the code for downloading from an ftp server? if you have it can you please send it through pm or reply to this comment or can you link a video that will have the download coding work side by side your code. Thank you very much for the upload part!

  5. How should i activate "background worker" code? Background worker code take params from struct? And the last one how can i handle exceptions? If exception will appear do that code will "think" that uploading is finished? Thank you.

  6. @Fox Learn : does not work – Pls can you sent me the source code? Email: [email protected]

    My Code (does not work):

    // !!! Attention: My progressBar have another Name: progressBarUpload (in the Video only "progressBar")
    //Projectname == namespace == ftptest

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    namespace ftptest
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    struct FtpSetting
    {
    public string Server { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string FileName { get; set; }
    public string FullName { get; set; }
    }

    FtpSetting _inputParameter;

    private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
    string fileName = ((FtpSetting)e.Argument).FileName;
    string fullName = ((FtpSetting)e.Argument).FileName;
    string userName = ((FtpSetting)e.Argument).FileName;
    string password = ((FtpSetting)e.Argument).FileName;
    string server = ((FtpSetting)e.Argument).FileName;
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", server, fileName)));
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(userName, password);
    Stream ftpStream = request.GetRequestStream();
    FileStream fs = File.OpenRead(fullName);
    byte[] buffer = new byte[1024];
    double total = (double)fs.Length;
    int byteRead = 0;
    double read = 0;
    do
    {
    if (!backgroundWorker.CancellationPending)
    {
    byteRead = fs.Read(buffer, 0, 1024);
    ftpStream.Write(buffer, 0, byteRead);
    read += (double)byteRead;
    double percentage = read / total * 100;
    backgroundWorker.ReportProgress((int)percentage);
    }
    }
    while (byteRead != 0);
    fs.Close();
    ftpStream.Close();
    }

    private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    lblStatus.Text = $"Uploaded {e.ProgressPercentage} %";
    progressBarUpload.Value = e.ProgressPercentage;
    progressBarUpload.Update();
    }

    private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    lblStatus.Text = "Upload abgeschlossen!";
    }

    private void btnUpload_Click(object sender, EventArgs e)
    {
    using (OpenFileDialog ofd = new OpenFileDialog() { Multiselect = false, ValidateNames = true, Filter = "All files|*.*" })
    {
    if (ofd.ShowDialog() == DialogResult.OK)
    {
    FileInfo fi = new FileInfo(ofd.FileName);
    _inputParameter.Username = txtUserName.Text;
    _inputParameter.Password = txtPassword.Text;
    _inputParameter.Server = txtServer.Text;
    _inputParameter.FileName = fi.Name;
    _inputParameter.FullName = fi.FullName;
    }
    }
    }
    }
    }

  7. very nice video Fox Learn! hey guys you need this code: private void btnFtp_Click(object sender, EventArgs e)
    {
    using (OpenFileDialog ofd = new OpenFileDialog() { Multiselect = false, ValidateNames = true, Filter = "all files|*.*" })
    {
    if (ofd.ShowDialog() == DialogResult.OK)
    {
    FileInfo fi = new FileInfo(ofd.FileName);
    _inputParameter.UserName = txtUser.Text;
    _inputParameter.Password = txtPass.Text;
    _inputParameter.Server = txtServer.Text;
    _inputParameter.FileName = fi.Name;
    _inputParameter.FullName = fi.FullName;
    //this line XD
    backgroundWorker.RunWorkerAsync(_inputParameter);
    }
    }
    }

  8. Music should have been avoided, and each line should have been explained, that really would have helped a lot one more important thing is first and foremost the FTPwebrequest class should have been explained;
    Still good jod
    Hats Up

  9. This is missing from the video:
    private void btnUpload_Click(object sender, EventArgs e)
    {
    using (OpenFileDialog ofd = new OpenFileDialog() { Multiselect = false, ValidateNames = true, Filter = "All files|*.*" })
    {
    if(ofd.ShowDialog() == DialogResult.OK)
    {
    FileInfo fi = new FileInfo(ofd.FileName);
    _inputParameter.UserName = txtUserName.Text;
    _inputParameter.Password = txtPassword.Text;
    _inputParameter.Server = txtServer.Text;
    _inputParameter.FileName = fi.Name;
    _inputParameter.FullName = fi.FullName;
    backgroundWorker.RunWorkerAsync(_inputParameter);
    }
    }
    }

  10. this line of code needs to be added to the click event of the upload button

    backgroundWorker.RunWorkerAsync(_inputParameter);

  11. When I try to upload a file, the program does not load it, it simply does nothing. Could you help me solve it please?

  12. The remote server returned an error: (550) File unavailable (e.g., file not found, no access).

  13. it doesnt work i followed tutorial but when i upload file progress bar shows nothing and it stays at 0% and doesnt upload file?what might be the issue?
    can you email me kindly on:[email protected])

  14. null refernce exception on FileName:Object reference not set to an instance of an object
    if we add this.backgroundWorker1.RunWorkerAsync();
    in buttonclick
    i dont know how every one got this working with above code but the code in video needs some changes to run these are the changes
    first you need to place backgroundWorker1.RunWorkerAsync(); in the end of the upload button.
    then you need to change:-
    string fileName = ((ftpSetting)e.Argument).FileName;

    string FullName = ((ftpSetting)e.Argument).FullName;

    string Username = ((ftpSetting)e.Argument).Username;

    string passowrd = ((ftpSetting)e.Argument).Username;

    string server = ((ftpSetting)e.Argument).Server;
    above into below:-
    string fileName = _inputParameter.FileName;

    string fullName = _inputParameter.FullName;

    string userName =_inputParameter.Username;

    string passowrd = _inputParameter.Password;

    string server = _inputParameter.Server;
    only after this i got to run my code

  15. Hi, dear Fox Learn! Thank you for the video! It is great!

    Unfortunately i have met a problem when tried to force my console application send the file to the server.

    I receiving an Unhandled Exception: System.UriFormatException: Invalid URI: The hostname could not be parsed.

    In this line:

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0},{1}", server, filename)));

    When i click on the link which i use as a "server", in Google Chrome it leads me to the server without any problems.

    I want to ask you about some advise. What shoud i change or do for fix this problem? Thanks in advance!

Leave a Reply

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