gpt4 book ai didi

c# - 从 ftp 服务器下载文件时为 "The underlying connection was closed"

转载 作者:可可西里 更新时间:2023-11-01 08:29:12 26 4
gpt4 key购买 nike

我想从 ftp 服务器下载文件。我写了下面的代码来从 ftp 下载文件

public void downloadFile(string FTPAddress, string filename, string username, string password, string destFile)
{
try
{
FtpWebRequest request = FtpWebRequest.Create(FTPAddress + filename) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.UseBinary = true;
request.KeepAlive = false; //close the connection when done
request.Timeout = 60000;
//Streams
using (var response = request.GetResponse())
{

using (Stream reader = response.GetResponseStream())
{
byte[] buffer = new byte[1024];
using (Stream streamFile = File.Create(destFile))
{
while (true)
{
int bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
break;
}
else
{
streamFile.Write(buffer, 0, bytesRead);

}
}
}
}
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}

但是当运行这段代码时出现异常:

The underlying connection was closed: An unexpected error occurred on a receive.

有什么问题可以帮助我...

最佳答案

建议 1:明确将超时设置为无限。

request.Timeout = -1;

建议 2:捕获更具体的异常类型 WebException,并检查 WebExceptionStatus。

建议 3:打开 System.Net 的跟踪。

我已经为不适用于您的情况的两个来源设置了 TraceLevel。

How to: Configure Network Tracing

<configuration>
<system.diagnostics>
<sources>
<source name="System.Net" tracemode="includehex" maxdatasize="1024">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.Cache">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.Http">
<listeners>
<add name="System.Net "/>
</listeners>
</source>
<source name="System.Net.Sockets">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
<source name="System.Net.WebSockets">
<listeners>
<add name="System.Net"/>
</listeners>
</source>
</sources>
<switches>
<add name="System.Net" value="Verbose"/>
<add name="System.Net.Cache" value="Off"/>
<add name="System.Net.Http" value="Off"/>
<add name="System.Net.Sockets" value="Verbose"/>
<add name="System.Net.WebSockets" value="Off"/>
</switches>
<sharedListeners>
<add name="System.Net"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="network.log"
/>
</sharedListeners>
<trace autoflush="true"/>
</system.diagnostics>
</configuration>

关于c# - 从 ftp 服务器下载文件时为 "The underlying connection was closed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11432101/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com