Upload file and download file from FTP

32,307

Solution 1

Both WebClient.UploadFile and WebClient.DownloadFile work correctly for FTP as well as binary files.


Upload

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.UploadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

If you need a greater control, that WebClient does not offer (like TLS/SSL encryption, ascii/text transfer mode, transfer resuming, etc), use FtpWebRequest. Easy way is to just copy a FileStream to FTP stream using Stream.CopyTo:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.UploadFile;  

using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip"))
using (Stream ftpStream = request.GetRequestStream())
{
    fileStream.CopyTo(ftpStream);
}

If you need to monitor an upload progress, you have to copy the contents by chunks yourself:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.UploadFile;  

using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip"))
using (Stream ftpStream = request.GetRequestStream())
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        ftpStream.Write(buffer, 0, read);
        Console.WriteLine("Uploaded {0} bytes", fileStream.Position);
    } 
}

For GUI progress (WinForms ProgressBar), see:
How can we show progress bar for upload with FtpWebRequest

If you want to upload all files from a folder, see
Recursive upload to FTP server in C#.


Download

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

If you need a greater control, that WebClient does not offer (like TLS/SSL encryption, ascii/text transfer mode, resuming transfers, etc), use FtpWebRequest. Easy way is to just copy an FTP response stream to FileStream using Stream.CopyTo:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    ftpStream.CopyTo(fileStream);
}

If you need to monitor a download progress, you have to copy the contents by chunks yourself:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileStream.Write(buffer, 0, read);
        Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
    }
}

For GUI progress (WinForms ProgressBar), see:
FtpWebRequest FTP download with ProgressBar

If you want to download all files from a remote folder, see
C# Download all files and subdirectories through FTP.

Solution 2

You need to say whether you're uploading text or binary files. Add the following line after request is declared & initialised:

request.UseBinary = true;

http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.usebinary.aspx

Solution 3

Uploading is easy...

void Upload(){
    Web client = new WebClient();
    client.Credentials = new NetworkCredential(username, password);
    client.BaseAddress = "ftp://ftpsample.net/";

    client.UploadFile("sample.txt", "sample.txt"); //since the baseaddress
}


Downloading is easy too... The code I made below uses BackgroundWorker (so it doesn't freeze the interface/application when download starts). Plus, I shortened the code with the use of lambda (=>).
void Download(){
    Web client = new WebClient();
    client.Credentials = new NetworkCredential(username, password);

    BackgroundWorker bg = new BackgroundWorker();
    bg.DoWork += (s, e) => { 
        client.DownloadFile("ftp://ftpsample.net/sample.zip", "sample.zip"); 
    };
    bg.RunWorkerCompleted += (s, e) => { //when download is completed
        MessageBox.Show("done downloading");
        download1.Enabled = true; //enable download button
        progressBar.Value = 0; // reset progressBar
    };
    bg.RunWorkerAsync();
    download1.Enabled = false; //disable download button 
    while (bg.IsBusy)
    {
        progressBar.Increment(1); //well just for extra/loading
        Application.DoEvents(); //processes all windows messages currently in the message queue
    }
}

You can also use DownloadFileAsync method to show real progress file downloading:

client.DownloadFileAsync(new Uri("ftp://ftpsample.net/sample.zip"), "sample.zip");
client.DownloadProgressChanged += (s, e) =>
{
    progressBar.Value = e.ProgressPercentage; //show real download progress
};
client.DownloadFileCompleted += (s, e) =>
{
    progressBar.Visible = false;
    // other codes after the download
};
//You can remove the 'while' statement and use this ^
Share:
32,307
Spreadzz
Author by

Spreadzz

Updated on July 09, 2022

Comments

  • Spreadzz
    Spreadzz almost 2 years

    I am trying to make a program that uploads/downloads .exe file to a FTP

    I tried using FtpWebRequest, but I only succeed to upload and download .txt files.

    Then i found here a solution for downloading using the WebClient:

    WebClient request = new WebClient();
    request.Credentials = new NetworkCredential("username", "password");
    byte[] fileData =  request.DownloadData("ftp://myFTP.net/");
    
    FileStream file = File.Create(destinatie);
    file.Write(fileData, 0, fileData.Length);
    
    file.Close();
    

    This solution works. But I seen that WebClient has a method DownloadFile which did not worked. I think because it doesn't work on FTP only on HTTP. Is my assumption true? If not how can I get it to work?

    And is there any other solution for uploading/downloading a .exe file to ftp using FtpWebRequest?