gpt4 book ai didi

c# - 使用 FtpWebRequest 下载文件

转载 作者:太空狗 更新时间:2023-10-29 18:01:33 24 4
gpt4 key购买 nike

我正在尝试使用 FtpWebRequest 下载文件。

private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath)
{
int bytesRead = 0;
byte[] buffer = new byte[1024];

FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, true);
request.Method = WebRequestMethods.Ftp.DownloadFile;

Stream reader = request.GetResponse().GetResponseStream();
BinaryWriter writer = new BinaryWriter(File.Open(localDestinationFilePath, FileMode.CreateNew));

while (true)
{
bytesRead = reader.Read(buffer, 0, buffer.Length);

if (bytesRead == 0)
break;

writer.Write(buffer, 0, bytesRead);
}
}

它使用我创建的这个 CreateFtpWebRequest 方法:

private FtpWebRequest CreateFtpWebRequest(string ftpDirectoryPath, string userName, string password, bool keepAlive = false)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ftpDirectoryPath));

//Set proxy to null. Under current configuration if this option is not set then the proxy that is used will get an html response from the web content gateway (firewall monitoring system)
request.Proxy = null;

request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = keepAlive;

request.Credentials = new NetworkCredential(userName, password);

return request;
}

它下载它。但是信息总是损坏的。有人知道这是怎么回事吗?

最佳答案

刚想通了:

    private void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath)
{
int bytesRead = 0;
byte[] buffer = new byte[2048];

FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, true);
request.Method = WebRequestMethods.Ftp.DownloadFile;

Stream reader = request.GetResponse().GetResponseStream();
FileStream fileStream = new FileStream(localDestinationFilePath, FileMode.Create);

while (true)
{
bytesRead = reader.Read(buffer, 0, buffer.Length);

if (bytesRead == 0)
break;

fileStream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
}

不得不改用 FileStream。

关于c# - 使用 FtpWebRequest 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12519290/

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