C# 如何在C语言中中断服务器连接#
我的应用程序的一个特点是从ftp服务器下载文件。当然,此功能要求取消此操作(取消下载) 现在,我的下载功能如下:C# 如何在C语言中中断服务器连接#,c#,ftp,C#,Ftp,我的应用程序的一个特点是从ftp服务器下载文件。当然,此功能要求取消此操作(取消下载) 现在,我的下载功能如下: try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + uri + "/" + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; req
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块中看到,当用户点击Cancel按钮时,我试图中断这个连接
- 取消操作场景:
那么如何避免这种异常呢?我假设您有某种形式的表单,因此您可以在线程上执行下载 您最好在while循环中检查一个“cancel”标志 例如 然后让你的方法优雅地取消
其次,您应该在流上使用using语句。这意味着,如果您抛出异常,finally块将保证您的流被释放(顺便说一句,这就是为什么您将接收文件繁忙,因为流尚未运行析构函数,即使您的方法已完成)我假设您有某种形式,因此,您需要在线程上执行下载 您最好在while循环中检查一个“cancel”标志 例如 然后让你的方法优雅地取消
其次,您应该在流上使用using语句。这意味着,如果您抛出异常,finally块将保证您的流被释放(顺便说一句,这就是为什么您将接收文件繁忙,因为流尚未运行析构函数,即使您的方法已完成)我将该标志添加到我的循环中,但当它到达outputStream.Close of response.Close()时仍然如此;或ftpStream.close()station它抛出一个异常,表示文件不可用(例如文件正忙)。您是否在“取消”方法中删除了与流有关的代码?删除线程中止,然后“尝试”加入线程。如果需要的时间太长,您可能需要中止它。第二,哪一行抛出异常。如果您查看异常的详细信息,它会告诉您;或ftpStream.close()station它抛出一个异常,表示文件不可用(例如文件正忙)。您是否在“取消”方法中删除了与流有关的代码?删除线程中止,然后“尝试”加入线程。如果需要的时间太长,您可能需要中止它。第二,哪一行抛出异常。如果您查看异常的详细信息,它会告诉您。
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();
while(readcount > 0 && !cancel)
{
...
}