1
我的一個應用程序功能是從我們的ftp服務器上下載文件。當然這個功能需要取消這個操作(取消下載)。現在如何在C#中斷服務器連接#
,我下載功能如下:
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塊看看你能看到,我想,當用戶點擊取消按鈕中斷此連接。
- 取消操作方案:被點擊
1)取消按鈕。
2)呼叫功能 「DoSomeWorx()」
3)在 「DoSomeWorx()」 做:
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();
問題是,當我到達任何的statments以下(ftpStream.Close();outputStream.Close();response.Close();)
它會拋出一個異常「文件不可用(例如,文件正忙)」
並且此異常會影響重新下載操作,因爲它會使文件看起來忙碌。
那麼如何避免這種異常?
我添加了標誌到我的循環,但仍然達到outputStream.Close response.close();或ftpStream.close()聲明它會拋出一個異常,說該文件不可用(例如文件忙) – BDeveloper 2009-04-12 12:37:23