Upload file and download file from FTP

后端 未结 3 1351
感动是毒
感动是毒 2020-11-28 14:47

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

I tried using FtpWebRequest, but I only succeed to upl

相关标签:
3条回答
  • 2020-11-28 15:21

    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, 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, 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.

    0 讨论(0)
  • 2020-11-28 15:22

    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

    0 讨论(0)
  • 2020-11-28 15:24

    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 ^
    
    0 讨论(0)
提交回复
热议问题