2016-05-01 5 views
0

У меня есть # домашнее задание C, чтобы создать менеджер загрузки для загрузки файла с сервера FTP, с этими условиями:Определение размера файла перед загрузкой с ftp-сервера? C# ошибка

  1. Выбор звукового файла на сервере.
  2. Обнаружение размера файла.
  3. Асинхронная передача файла на ваш рабочий компьютер через ftp.
  4. Представление прогресса загрузки.

На самом деле, я закончил три из них, почти все, за исключением некоторых ошибка со вторым условием, когда я попытался получить размер файла перед загрузкой, моя программа разбился и ошибка произошла так:

Error

Это код для моего загрузчика:

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

namespace DownloadDataFTP 
{ 
    public partial class ftpForm : Form 
    { 
     public ftpForm() 
     { 
      InitializeComponent(); 
     } 

    private byte[] downloadedData; 

    //Connects to the FTP server and downloads the file 
    private void downloadFile(string FTPAddress, string filename, string username, string password) 
    { 
     downloadedData = new byte[0]; 

     try 
     { 
      //Create FTP request 
      //Note: format is ftp://server.com/file.ext 
      FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest; 


      //Get the file size first (for progress bar) 
      request.Method = WebRequestMethods.Ftp.GetFileSize; 
      request.Credentials = new NetworkCredential(username, password); 
      request.UsePassive = true; 
      request.UseBinary = true; 
      request.KeepAlive = true; //don't close the connection 

      int dataLength = (int)request.GetResponse().ContentLength; 


      //Now get the actual data 
      request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest; 

      request.Method = WebRequestMethods.Ftp.DownloadFile; 
      request.Credentials = new NetworkCredential(username, password); 
      request.UsePassive = true; 
      request.UseBinary = true; 
      request.KeepAlive = false; //close the connection when done 

      //Set up progress bar 
      progressBar1.Value = 0; 
      progressBar1.Maximum = dataLength; 
      lbProgress.Text = "0/" + dataLength.ToString(); 

      //Streams 
      FtpWebResponse response = request.GetResponse() as FtpWebResponse; 
      Stream reader = response.GetResponseStream(); 

      //Download to memory 
      //Note: adjust the streams here to download directly to the hard drive 
      MemoryStream memStream = new MemoryStream(); 
      byte[] buffer = new byte[1024]; //downloads in chuncks 

      while (true) 
      { 
       Application.DoEvents(); //prevent application from crashing 

       //Try to read the data 
       int bytesRead = reader.Read(buffer, 0, buffer.Length); 

       if (bytesRead == 0) 
       { 
        //Nothing was read, finished downloading 
        progressBar1.Value = progressBar1.Maximum; 
        lbProgress.Text = dataLength.ToString() + "/" + dataLength.ToString(); 

        Application.DoEvents(); 
        break; 
       } 
       else 
       { 
        //Write the downloaded data 
        memStream.Write(buffer, 0, bytesRead); 

        //Update the progress bar 
        if (progressBar1.Value + bytesRead <= progressBar1.Maximum) 
        { 
         progressBar1.Value += bytesRead; 
         lbProgress.Text = progressBar1.Value.ToString() + "/" + dataLength.ToString(); 

         progressBar1.Refresh(); 
         Application.DoEvents(); 
        } 
       } 
      } 

      //Convert the downloaded stream to a byte array 
      downloadedData = memStream.ToArray(); 

      //Clean up 
      reader.Close(); 
      memStream.Close(); 
      response.Close(); 

      MessageBox.Show("Downloaded Successfully"); 
     } 
     catch (Exception) 
     { 
      MessageBox.Show("There was an error connecting to the FTP Server."); 
     } 

     txtData.Text = downloadedData.Length.ToString(); 
     this.Text = "Download and Upload Data through FTP"; 

     username = string.Empty; 
     password = string.Empty; 
    } 

    //Upload file via FTP 
    private void Upload(string FTPAddress, string filePath, string username, string password) 
    { 
     //Create FTP request 
     FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress + "/" + Path.GetFileName(filePath)); 

     request.Method = WebRequestMethods.Ftp.UploadFile; 
     request.Credentials = new NetworkCredential(username, password); 
     request.UsePassive = true; 
     request.UseBinary = true; 
     request.KeepAlive = false; 

     //Load the file 
     FileStream stream = File.OpenRead(filePath); 
     byte[] buffer = new byte[stream.Length]; 

     stream.Read(buffer, 0, buffer.Length); 
     stream.Close(); 

     //Upload file 
     Stream reqStream = request.GetRequestStream(); 
     reqStream.Write(buffer, 0, buffer.Length); 
     reqStream.Close(); 

     MessageBox.Show("Uploaded Successfully"); 
    } 

    //get file size for downloading 
    private void FileSize_down(string FTPAddress, string filename) 
    { 
     FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest; 
     request.Method = WebRequestMethods.Ftp.GetFileSize; 


     long dataLength = (long)request.GetResponse().ContentLength; 
     sizeFile.Text = dataLength.ToString(); 
    } 

    //get file size for uploading 
    private void FileSize_up(string filename) 
    { 
     if (UpFile.Text != "") 
     { 
      //direction file 
      FileInfo f = new FileInfo(UpFile.Text); 
      //add size to text box 
      textBox1.Text = f.Length.ToString(); 
     } 
     else 
      MessageBox.Show("Choose file to upload"); 
    } 

    //Connects to the FTP server and request the list of available files 
    private void getFileList(string FTPAddress, string username, string password) 
    { 
     List<string> files = new List<string>(); 

     try 
     { 
      //Create FTP request 
      FtpWebRequest request = FtpWebRequest.Create(FTPAddress) as FtpWebRequest; 

      request.Method = WebRequestMethods.Ftp.ListDirectory; 
      request.Credentials = new NetworkCredential(username, password); 
      request.UsePassive = true; 
      request.UseBinary = true; 
      request.KeepAlive = false; 


      FtpWebResponse response = request.GetResponse() as FtpWebResponse; 
      Stream responseStream = response.GetResponseStream(); 
      StreamReader reader = new StreamReader(responseStream); 

      while (!reader.EndOfStream) 
      { 
       Application.DoEvents(); 
       files.Add(reader.ReadLine()); 
      } 

      //Clean-up 
      reader.Close(); 
      responseStream.Close(); //redundant 
      response.Close(); 
     } 
     catch (Exception) 
     { 
      MessageBox.Show("There was an error connecting to the FTP Server"); 
     } 

     username = string.Empty; 
     password = string.Empty; 

     this.Text = "Download and Upload Data through FTP"; //Back to normal title 

     //If the list was successfully received, display it to the user 
     //through a dialog 
     if (files.Count != 0) 
     { 
      listDialogForm dialog = new listDialogForm(files); 
      if (dialog.ShowDialog() == DialogResult.OK) 
      { 
       //Update the File Name field 
       txtFileName.Text = dialog.ChosenFile; 
      } 
     } 
    } 

    //Make sure the FTP server address has ftp:// at the beginning 
    private void txtFTPAddress_Leave(object sender, EventArgs e) 
    { 
     if (!txtFTPAddress.Text.StartsWith("ftp://")) 
      txtFTPAddress.Text = "ftp://" + txtFTPAddress.Text; 
    } 

Это та часть, которая получает файл размер для скачивания.

//get file size for downloading 
    private void FileSize_down(string FTPAddress, string filename) 
    { 
     FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest; 
     request.Method = WebRequestMethods.Ftp.GetFileSize; 


     long dataLength = (long)request.GetResponse().ContentLength; 
     sizeFile.Text = dataLength.ToString(); 
    } 

Большое спасибо!

+0

Обратите внимание, что не всегда возможно заранее определить размер: иногда содержимое создается динамически, и сервер не может/не хочет заранее указывать размер. –

+0

Я тестировал его с помощью своего собственного FTP-сервера FileZilla. Вы имеете в виду, что ошибка могла произойти с сервера, и я должен сначала проверить свой сервер? Я просто следую инструкциям [здесь] (http://www.noip.com/support/knowledgebase/setting-up-a-ftp-server-on-your-home-computer/) для создания ftp-сервера. –

ответ

0

Вы получили ошибку 530 (не вошел в систему). Похоже, это проблема. В ваших других методах (DownloadFile, GetFileList и т.д.) вы включаете в себя:

request.Credentials = new NetworkCredential(username, password); 
    request.UsePassive = true; 
    request.UseBinary = true; 
    request.KeepAlive = false; 

в вашем Filesize_down вы не делаете.

+0

Спасибо, что отлично сработал после включения этого. –

Смежные вопросы