Одной из особенностей моего приложения является загрузка файлов с нашего ftp-сервера. И, конечно, эта функция требует отмены этой операции (Отмена загрузки).
Теперь моя функция загрузки выглядит следующим образом:
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + uri + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.UsePassive = true;
response = (FtpWebResponse)reqFTP.GetResponse();
ftpStream = response.GetResponseStream();
_isItOutputStream = true;
string dataLengthString = response.Headers["Content-Length"];
int dataLength = 0;
if (dataLengthString != null)
{
dataLength = Convert.ToInt32(dataLengthString);
}
long cl = response.ContentLength;
int bufferSize = 4048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
bool first = true;
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
_actualDownloaded += readCount;
if (this.InvokeRequired)
{
ProgressBarDel _progressDel = new ProgressBarDel(ProgressBar);
this.Invoke(_progressDel, new object[] { _actualDownloaded, first });
}
first = false;
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
_isItOutputStream = false;
return true;
}
catch (Exception ee)
{
_downloadException = ee.Message;
if (ftpStream != null && outputStream!=null )
if (ftpStream.CanRead && outputStream.CanWrite)
{
ftpStream.Close();
outputStream.Close();
}
if (response != null)
response.Close();
return false;
}
Теперь, как вы видите в Catch Block, вы видите, что я пытаюсь прервать это соединение, когда пользователь нажимает кнопку Отмена.
- Сценарий отмены операции:
1) Нажата кнопка «Отмена».
2) Вызов функции «DoSomeWorx ()»
3) в "DoSomeWorx ()" do:
if (_isItOutputStream)// where here i'm trying to check if it's downloading
{
ftpStream.Close();
outputStream.Close();
response.Close();
}
if (_startCopy)// check if copying to phone
{
IsCancelled();
}
_btnDownload2PhoneThread.Abort(); // actually this operation does what i did before but for some resoans it does this but it takes time...
_btnDownload2PhoneThread.Join();
Проблема в том, что я достигаю любой из следующих характеристик (ftpStream.Close();outputStream.Close();response.Close();)
выдает исключение «Файл недоступен (например, файл занят)»
и это исключение влияет на операцию повторной загрузки, когда он видит, что файл занят.
так как избежать этого исключения?