Отправка файла из веб-заданий Azure с использованием FTP - PullRequest
0 голосов
/ 18 октября 2018

У меня 1 проблема, когда я пытаюсь отправить файл по FTP из Azure WebJobs.Этот бросок поочередно «Удаленный сервер возвратил ошибку: (530) Не вошел в систему», мой код прекрасно работает в localhost (на компьютере разработчика).

Я прочитал все эти сообщения, но не нашел пути:

FTPWebRequest 530 Ошибка: не зарегистрировано в проблеме

FTP Удаленный сервер возвратил ошибку: (530) Не вошел в систему

Извлечение файлов с FTP-сервера через веб-задания Azure

Ftp на внешнийсервер в Azure. Веб-работа не работает

Другое, но у меня в службе приложений только 1 веб-работа, а загрузка ЦП составляла 30% при выполнении заданий .. Не удается загрузить файл с FTP только в Azureвеб-приложение

Редактировать: Каталог создания кода

FtpWebRequest reqFTP = null;
        Stream ftpStream = null;

        string[] subDirs = directory.Split('/');

        string currentDir = publishUrl;

        foreach (string subDir in subDirs)
        {
            try
            {
                currentDir = currentDir + "/" + subDir;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(currentDir);
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                reqFTP.UseBinary = true;
                //reqFTP.UsePassive = true;
                //reqFTP.KeepAlive = true;
                reqFTP.Credentials = new NetworkCredential(userName, userPWD);
                FtpWebResponse response =  (FtpWebResponse)await reqFTP.GetResponseAsync();
                ftpStream = response.GetResponseStream();
                ftpStream.Close();
                response.Close();
            }
            catch (Exception exception)
            {

                Console.WriteLine(exception.Message);
                //directory already exist I know that is weak but there is no way to check if a folder exist on ftp...
            }
        }

Файл отправки кода:

        try
        {
            using (WebClient client = new WebClient())
            {
                client.Credentials = new NetworkCredential(userName, userPWD);
                client.UploadFile(publishUrl, "STOR", localFileName);
                return true;
            }
        }
        catch (Exception exception)
        {
            //Console.Error.Write(exception.Message);
            Console.WriteLine(exception.Message);
            return false;
        }

И регистрировать, когда я запускаю код в веб-приложениях Azure WebApp (Ошибка)): https://pastebin.com/vgTxqT5p

И регистрировать, когда я запускаю код на локальной машине (Work Great): https://pastebin.com/hBpum8T0

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

У кого-нибудь есть способ?Спасибо заранее.

1 Ответ

0 голосов
/ 18 октября 2018

Плохой способ (и мне это не понравилось), но это работает .....:

Измените функцию создания каталога следующим образом:

public static void MakeFTPDir(string publishUrl, string userName, string userPWD, string directory)
    {
        FtpWebRequest reqFTP = null;
        Stream ftpStream = null;

        string[] subDirs = directory.Split('/');

        string currentDir = publishUrl;

        foreach (string subDir in subDirs)
        {
            bool isNotCreated = true;
            int iTentative = 0;
            currentDir = currentDir + "/" + subDir;
            while (isNotCreated)
            {
                iTentative++;
                try
                {
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(currentDir);
                    reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                    reqFTP.UseBinary = true;
                    reqFTP.UsePassive = true;
                    reqFTP.KeepAlive = true;
                    reqFTP.Credentials = new NetworkCredential(userName, userPWD);
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    ftpStream = response.GetResponseStream();
                    ftpStream.Close();
                    response.Close();
                }
                catch(WebException webException)
                {
                    FtpWebResponse excWebResponse = (FtpWebResponse)webException.Response;
                    if(excWebResponse.StatusCode == FtpStatusCode.NotLoggedIn)
                    {
                        Console.WriteLine("WebException ==> NotLoggedIn >> Tentative :" + iTentative);
                        isNotCreated = true;
                    }
                    else
                    {
                        Console.WriteLine(webException.Message);
                        isNotCreated = false;
                    }
                }
                catch (Exception exception)
                {
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    if (response.StatusCode == FtpStatusCode.NotLoggedIn)
                    {
                        Console.WriteLine("Exception ==> NotLoggedIn >> Tentative :" + iTentative);
                        isNotCreated = true;
                    }
                    else
                    {
                        Console.WriteLine(exception.Message);
                        isNotCreated = false;
                    }
                }
            }
        }
    }

Измените файл отправкивот так:

 public static bool SendFtpFile(string publishUrl, string userName, string userPWD, string localFileName)
    {
        bool isNotCreated = true;
        int iTentative = 0;
        while (isNotCreated)
        {
            iTentative++;
            try
            {
                using (WebClient client = new WebClient())
                {
                    client.Credentials = new NetworkCredential(userName, userPWD);
                    client.UploadFile(publishUrl, "STOR", localFileName);
                    return true;
                }
            }
            catch (WebException webException)
            {
                FtpWebResponse excWebResponse = (FtpWebResponse)webException.Response;
                if (excWebResponse.StatusCode == FtpStatusCode.NotLoggedIn)
                {
                    Console.WriteLine("WebException ==> NotLoggedIn >> Tentative :" + iTentative);
                    isNotCreated = true;
                }
                else
                {
                    Console.WriteLine(webException.Message);
                    return false;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
                return false;
            }
        }
        return true;
    }

Измените IfFileExistOnServer:

public static bool CheckIfFileExistsOnServer(string publishUrl, string userName, string userPWD, string fileName)
    {
        bool isNoCheck = true;
        int iTentative = 0;
        string azureBotUrl = publishUrl + "/" + fileName;

        while (isNoCheck)
        {
            iTentative++;
            try
            {
                var request = (FtpWebRequest)WebRequest.Create(azureBotUrl);
                request.Credentials = new NetworkCredential(userName, userPWD);
                request.UseBinary = true;
                request.UsePassive = true;
                request.KeepAlive = true;
                request.Method = WebRequestMethods.Ftp.GetFileSize;
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                return true;
            }
            catch (WebException webException)
            {
                FtpWebResponse excWebResponse = (FtpWebResponse)webException.Response;
                if (excWebResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                    return false;
                if (excWebResponse.StatusCode == FtpStatusCode.NotLoggedIn)
                {
                    Console.WriteLine("WebException ==> NotLoggedIn >> Tentative :" + iTentative);
                    isNoCheck = true;
                }
                else
                {
                    return false;
                }
            }
        }
        return false;
    }

И измените RenameFileOnServer:

public static bool RenameFileOnServer(string publishUrl, string userName, string userPWD, string sourceFileName, string newFileName)
    {
        bool isNoRenameFile = true;
        int iTentative = 0;
        FtpWebRequest ftpRequest = null;
        FtpWebResponse ftpResponse = null;
        string azureBotUrl = publishUrl + "/" + sourceFileName;
        while (isNoRenameFile)
        {
            iTentative++;
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(azureBotUrl);
                ftpRequest.Credentials = new NetworkCredential(userName, userPWD);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.Rename;
                ftpRequest.RenameTo = newFileName.Split('\\')[newFileName.Split('\\').Length - 1];
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpResponse.Close();
                ftpRequest = null;
                return true;
            }
            catch (WebException webException)
            {
                FtpWebResponse excWebResponse = (FtpWebResponse)webException.Response;
                if (excWebResponse.StatusCode == FtpStatusCode.NotLoggedIn)
                {
                    Console.WriteLine("WebException ==> NotLoggedIn >> Tentative :" + iTentative);
                    isNoRenameFile = true;
                }
                else
                {
                    return false;
                }
                Console.WriteLine(webException.Message);
            }
            catch (Exception)
            {
                return false;
            }
        }
        return false;
    }

Я жду звонка от службы поддержки Ms Azure..

...