2015-10-31 6 views
0

Я создаю форму окна для загрузки файлов с ftp из определенной папки.Как загрузить файлы с ftp из определенной папки

Пользователь поместил данные ftp с именем пользователя и паролем и именем папки, из которого будет загружен все файлы. Это будет установлено пользователем один раз, и весь файл из ftp описательной папки будет загружаться каждый день.
Пример имени FTP-папки - это MyFolder, где a.docx, b.docx и т. Д. Загружают данные a.docx, b.docx, а не другие данные папки, которые необходимо загрузить.

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

private void downloadFileFromFTP() 
{ 
    try 
    { 
     string[] files = GetFileList(); 
     foreach (string file in files) 
     { 
      Download(file); 
     } 
    } 
    catch (Exception ex) 
    { 
    } 
} 

Для получения списка файлов

public string[] GetFileList() 
{ 
    string[] downloadFiles; 
    StringBuilder result = new StringBuilder(); 
    WebResponse response = null; 
    StreamReader reader = null; 
    try 
    { 
     FtpWebRequest reqFTP; 
     reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + txtftpAddress.Text + "/")); //txtFtpAddress.Text + "/" + txtFTPFolderName + "/" + file 
     reqFTP.UseBinary = true; 
     reqFTP.Credentials = new NetworkCredential("UserNm", "passwd"); 
     reqFTP.Method = WebRequestMethods.Ftp .ListDirectory; 
     reqFTP.Proxy = null; 
     reqFTP.KeepAlive = false; 
     reqFTP.UsePassive = false; 
     response = reqFTP.GetResponse(); 
     reader = new StreamReader(response.GetResponseStream()); 
     string line = reader.ReadLine(); 
     while (line != null) 
     { 
      result.Append(line); 
      result.Append("\n"); 
      line = reader.ReadLine(); 
     } 
     // to remove the trailing '\n' 
     result.Remove(result.ToString().LastIndexOf('\n'), 1); 
     return result.ToString().Split('\n'); 
    } 
    catch (Exception ex) 
    { 
     if (reader != null) 
     { 
      reader.Close(); 
     } 
     if (response != null) 
     { 
      response.Close(); 
     } 
     downloadFiles = null; 
     return downloadFiles; 
    } 
} 

загрузить файл формирует папку

private void Download(string file) 
{      
    try 
    {        
     string uri = "ftp://" + txtFtpAddress.Text.Trim() + "/" + "txtlodername.Text" + "/" + file; 

     Uri serverUri = new Uri(uri); 
     if (serverUri.Scheme != Uri.UriSchemeFtp) 
     { 
      return; 
     }  
     FtpWebRequest reqFTP;     
     reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(txtFtpAddress.Text + "/" + txtFTPFolderName + "/" + file));         
     reqFTP.Credentials = new NetworkCredential("UserName", "mypass");     
     reqFTP.KeepAlive = false;     
     reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;         
     reqFTP.UseBinary = true; 
     reqFTP.Proxy = null;     
     reqFTP.UsePassive = false; 
     FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); 
     Stream responseStream = response.GetResponseStream(); 
     FileStream writeStream = new FileStream("D\\Temp" + file, FileMode.Create);     
     int Length = 2048; 
     Byte[] buffer = new Byte[Length]; 
     int bytesRead = responseStream.Read(buffer, 0, Length);    
     while (bytesRead > 0) 
     { 
      writeStream.Write(buffer, 0, bytesRead); 
      bytesRead = responseStream.Read(buffer, 0, Length); 
     }     
     writeStream.Close(); 
     response.Close(); 
    } 
    catch (WebException wEx) 
    { 
     MessageBox.Show(wEx.Message, "Download Error"); 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message, "Download Error"); 
    } 
} 

ответ

2

Я думаю, что 3 строки вашего метода Download должна быть исправлена ​​следующим образом:

1.

string uri = "ftp://" + txtFtpAddress.Text.Trim() + "/" + "txtlodername.Text" + "/" + file; 

должно быть:

string uri = "ftp://" + txtFtpAddress.Text.Trim() + "/" + txtFTPFolderName.Text.Trim() + "/" + file; 


2.

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(txtFtpAddress.Text + "/" + txtFTPFolderName + "/" + file)); 

должно быть:

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); 


3.

FileStream writeStream = new FileStream("D\\Temp" + file, FileMode.Create); 

должен быть:

FileStream writeStream = new FileStream("D:\\Temp\\" + file, FileMode.Create); 
+0

Спасибо за ваш быстрый ответ я делаю эти изменения моей проблема заключается в том, что как первый перечисляют все файлы в данной директории и вторым я хочу скачать только файл txtFTPFolderName в ftp, который описывается пользователем –

+0

Я хочу загрузить файл конкретной папки. Итак, сначала как я могу прочитать весь файл из определенной папки? Например, MyFolder содержит a.docx 'Мне нужно скачать только' a.docx' из ftp, а не другой файл –

+0

@ A.Goutam. Ваш метод 'GetFileList' выглядит хорошо, но' Uri' должен быть 'new Uri (" ftp: // "+ txtftpAddress.Text +"/"+" MyFolder "+"/")'. Затем разрешите пользователям выбирать перечисленные файлы. Элемент управления ListBox должен быть лучшим выбором. – jhmt

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