FtpWebRequest во время записи в поток, если сеть выходит из строя, тогда FTP-сервер выдает проблему отказа в доступе при попытке повторной загрузки - PullRequest
0 голосов
/ 22 августа 2011

Я использую FtpWebRequest для загрузки файла.Столкнувшись с проблемой, решение которой я не получаю.

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

Я установил TimeOut и ReadWriteTimeOut на 5 секунд FtpWebRequest на FTP-сервере, это 10 секунд.Даже если я попытаюсь загрузить один и тот же файл через час, проблема будет той же.

 // Get the object used to communicate with the server.
  request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + FtpInfo.FtpServer.Trim() + "/" + FtpInfo.FtpFolderPath.Trim() + "/" + FileName.Trim()));
   request.Method = WebRequestMethods.Ftp.UploadFile;
   request.Proxy = null;

   // FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential(FtpInfo.UserNameForFTP.Trim(), FtpInfo.PasswordForFTP.Trim());
    request.UsePassive = FtpInfo.UsePassive;
    request.KeepAlive = FtpInfo.KeepAlive;
    request.Timeout = FtpInfo.TimeOut; //Milliseconds
    request.UseBinary = true;
    request.ReadWriteTimeout = FtpInfo.TimeOut; //Milliseconds

                        FileInfo fi = new FileInfo(SourceLocation);
                        long length = fi.Length;
                        BytesUploaded = length;

                        long uploadSize = 0;
                        if (chunks == 0)
                        {
                            chunks = 1024;
                        }
                        else
                        {
                            buffLength = chunks;
                        }
                        byte[] buff = new byte[buffLength];
                        int contentLen;
                        using (FileStream fs = fi.OpenRead())
                        {
                            using (Stream strm = request.GetRequestStream())
                            {
                                contentLen = fs.Read(buff, 0, buffLength);
                                try
                                {
                                    while (contentLen != 0)
                                    {
                                        Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate() { lblProgress.Content = "Uploading '" + FileName + "'......" + "Bytes Uploaded (" + uploadSize.ToString() + "/" + length.ToString() + ")"; });
                                        strm.Write(buff, 0, contentLen);
                                        uploadSize += contentLen;
                                        contentLen = fs.Read(buff, 0, buffLength);
                                    }
                                    strm.Close();
                                }
                                catch (Exception ex)
                                {
                                    if (strm!=null)
                                    {
                                        try
                                        {
                                            strm.Close();
                                        }
                                        catch
                                        {
                                            throw ex;
                                        }
                                    }
                                    throw ex;
                                }
                            }
                            fs.Close();
                        }


                        try
                        {
                            //requestStream.Close(); -orignal
                            fi = null;
                            request=null;
                        }
                        catch { }

Ответы [ 2 ]

1 голос
/ 22 августа 2011

Я недостаточно знаю о вашем приложении (например, о загрузке по FTP в отдельном потоке), но попробуйте это:

bool DoneOK = false;
FtpWebRequest request = null;
FtpWebResponse response = null;
try {
    // Get the object used to communicate with the server.
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + FtpInfo.FtpServer.Trim() + "/" + FtpInfo.FtpFolderPath.Trim() + "/" + FileName.Trim()));
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Proxy = null;

    // FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential(FtpInfo.UserNameForFTP.Trim(), FtpInfo.PasswordForFTP.Trim());
    request.UsePassive = FtpInfo.UsePassive;
    request.KeepAlive = FtpInfo.KeepAlive;
    request.Timeout = FtpInfo.TimeOut; //Milliseconds
    request.UseBinary = true;
    request.ReadWriteTimeout = FtpInfo.TimeOut; //Milliseconds

    long length = new FileInfo(SourceLocation).Length;
    long uploadSize = 0;
    if ( chunks < 1 )
         chunks = 1024;

    buffLength = chunks;
    byte[] buff = new byte[buffLength];
    int contentLen = 0;
    string MSG = "";

    using (FileStream fs = File.OpenRead (SourceLocation))
    using (Stream strm = request.GetRequestStream())
    {
        while ((contentLen = fs.Read(buff, 0, buffLength)) > 0 )
        {
        MSG = "Uploading '" + FileName + "'......" + "Bytes Uploaded (" + uploadSize.ToString() + "/" + length.ToString() + ")";
        string tmp_MSG = MSG;
        Dispatcher.Invoke(DispatcherPriority.Normal, () => { lblProgress.Content = tmpMSG; });
        strm.Write(buff, 0, contentLen);
        uploadSize += contentLen;
        };

        strm.Close();

        // necessary - the upload occurs really here !
        response = (FtpWebResponse) request.GetResponse();
        // check the response codes... for example FileActionOK...
        if ( response.StatusCode == System.Net.FtpStatusCode.FileActionOK )
             DoneOK = true;

        response.Close(); response = null;
        request = null;
    }
    }
catch
{
};

if ( request != null )    
     {
     if ( response != null )
          {
          try { response.Close(); } catch {};
          response = null;
          }

     if ( !DoneOK )
          {
          try { request.Abort (); } catch {};
          }

     request = null;
     }
0 голосов
/ 17 сентября 2011

Это была проблема, связанная с используемым нами FTP-сервером, когда мы переключали FTP-сервер на IIS, тогда все работало гладко. Спасибо за помощь

...