«Тайм-аут операции в ftp» эта ошибка возникает при загрузке zip-файла с медленной сетью с сервера - PullRequest
2 голосов
/ 15 апреля 2019

Я использую ftp для загрузки zip-файла (размером от 10 МБ до 70 МБ) с сервера, который он прекрасно загружал, но когда сеть работает медленно, выдается ошибка the operation has timed out in ftp is showing, а затем возникает catch(Exception ex) в том, чтоdownload() вызывается еще раз, поэтому он снова и снова загружается.

Этот проект создан в .NET Framework 4.0

Я увеличил время ftpWebRequest.Timeout = 6000;, но все равно это не такt работа

public void Download(string localDirectory,string localFilename,string remoteDirectory,string remoteFileName) 
{

    string client_path=Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(localDirectory)));

    string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
    string configFile = System.IO.Path.Combine(appPath, "PACS.exe.config");

    ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
    configFileMap.ExeConfigFilename = configFile;

    System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

    config.AppSettings.Settings["client_path"].Value = client_path;
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");

    string str = Path.Combine(localDirectory, localFilename);
    FileInfo fileInfo = new FileInfo(str);
    FileStream fileStream = (FileStream)null;

    WebException webException;

    try
    {

        string path = Path.GetDirectoryName(Path.GetDirectoryName(remoteDirectory));

        string path1 = Path.GetDirectoryName(Path.GetDirectoryName(localDirectory));

        WebRequest sizeRequest = WebRequest.Create("ftp://" + "IP" + ":" + "port" + "/" + "C:\\KINSOLUTIONS\\Team\\Images\\1" + ".zip");

        sizeRequest.Credentials = (ICredentials)new NetworkCredential("UserName", "Password");

        sizeRequest.Method = WebRequestMethods.Ftp.GetFileSize;

        int size = (int)sizeRequest.GetResponse().ContentLength;

        FtpWebRequest ftpWebRequest = WebRequest.Create(new Uri("ftp://" + "IP" + ":" + "port" + "/" + "C:\\KINSOLUTIONS\\Team\\Images\\1" + ".zip")) as FtpWebRequest;

        ftpWebRequest.Credentials = (ICredentials)new NetworkCredential("UserName", "Password");

        ftpWebRequest.UsePassive = true;

        ftpWebRequest.Timeout = 6000;
        ftpWebRequest.KeepAlive = false;
        ftpWebRequest.Method = "RETR";
        ftpWebRequest.UseBinary = true;
        fileStream = new FileStream(path1 + ".zip", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);

        using(Stream responseStream = (ftpWebRequest.GetResponse() as FtpWebResponse).GetResponseStream())                
        {                   

            byte[] buffer = new byte[32768];

            int count = responseStream.Read(buffer, 0, 32768);                    

            long num = (long)count;                    

            int post = 0;

            while (size != post || count != 0 )
            {
                bool result = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
                while (!result)
                {
                    result = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
                    if (result)
                    {
                        fileStream.Close();
                        Download(localDirectory, localFilename, remoteDirectory, remoteFileName);
                    }
                }

                fileStream.Write(buffer, 0, count);
                count = responseStream.Read(buffer, 0, 32768);
                int position = (int)fileStream.Position;
                num += (long)count;                  
                post = position;
            }
            fileStream.Close();
        }
    }

    catch (WebException ex)
    {
        if (fileStream != null)
            fileStream.Close();                
            this.Download(localDirectory, localFilename, remoteDirectory, remoteFileName);
    }

    finally
    {
        if (fileStream != null)
            fileStream.Close();
    }
}

Есть ли другой способ загрузки файла zip в медленной сети?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...