Справочник.Получение файлов с FTP-сайта

#c# #asp.net #.net #ftp

#c# #asp.net #.net #ftp

Вопрос:

Я использую этот метод в своем asp.net приложение для переноса загружаемых файлов из локального каталога в хранилище Azure. Теперь я хочу сделать то же самое, но с файлами из папки FTP. Я изучил FtpWebRequest , но не уверен, как и будет ли это работать с этим текущим методом?

 foreach (string strFile in Directory.GetFiles("myftpsite", "*.jpg"))
{
    blob = blobContainer.GetBlobReference(strFile);
    blob.UploadFile(strFile);                
}
  

Комментарии:

1. Собираетесь ли вы отправлять их из контейнера больших двоичных объектов в физический файл в удаленном расположении?

2. Нет, он переходит из папки FTP В контейнер больших двоичных объектов

3. Вы не можете перейти прямо с FTP на BLOB. Где-то должен быть посредник.

4. ах, хорошо, вы знаете, почему это так?

Ответ №1:

Список всех файлов в папке FTP приведен в разделе:http://msdn.microsoft.com/en-us/library/ms229716.aspx

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

Комментарии:

1. Привет, файлы должны поступать прямо с FTP на большой двоичный объект, без участия локальной машины.

2. Ну, там, где вы выполняете код, наверняка есть оперативная память. Так, может быть, временно сохранить файлы там? Конечно, это не подходящее решение для очень больших файлов.

Ответ №2:

     public string[] directoryListDetailed(string directory)
    {
        try
        {
            /* Create an FTP Request */
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host   "/"   directory);
            /* Log in to the FTP Server with the User Name and Password Provided */
            ftpRequest.Credentials = new NetworkCredential(user, pass);
            /* When in doubt, use these options */
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;
            /* Specify the Type of FTP Request */
            ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
            /* Establish Return Communication with the FTP Server */
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            /* Establish Return Communication with the FTP Server */
            ftpStream = ftpResponse.GetResponseStream();
            /* Get the FTP Server's Response Stream */
            StreamReader ftpReader = new StreamReader(ftpStream);
            /* Store the Raw Response */
            string directoryRaw = null;
            /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
            try
            {

                string[] separator = { "", " " };
                while (ftpReader.Peek() != -1) 
                   {
                       bool flg = false; 

                     foreach (var word in ftpReader.ReadLine().Split (separator , StringSplitOptions.RemoveEmptyEntries))
                     {

                         if (flg == true)
                         { directoryRaw  = word.ToString()   "|"; flg = false; }
                         if (word.ToString () == "<DIR>")
                            flg = true;

                     }
                   } 
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            /* Resource Cleanup */
            ftpReader.Close();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
            /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
            try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        /* Return an Empty string Array if an Exception Occurs */
        return new string[] { "" };
    }
  

Комментарии:

1. -1 Вы пропустили разделение вашего потока и StreamReader на using блоки.