【发布时间】:2019-01-02 05:33:22
【问题描述】:
作为一名初级开发人员,我应该找到使用 ftp 下载文件的解决方案,并且我有此代码。
它可以工作,但有时我无法打开下载的文件。
public static bool DownloadDocument(string ftpPath, string downloadPath) {
bool retVal = false;
try {
Uri serverUri = new Uri(ftpPath);
if (serverUri.Scheme != Uri.UriSchemeFtp) {
return false;
}
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(ftpPath);
reqFTP.Credentials = new NetworkCredential(Tools.FtpUserName, Tools.FtpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
using (FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse()) {
using (Stream responseStream = response.GetResponseStream()) {
using (FileStream writeStream = new FileStream(downloadPath, FileMode.Create)) {
int Length = 1024 * 1024 * 30;
Byte[] buffer = new Byte[Length];
responseStream.Read(buffer, 0, Length);
}
}
}
retVal = true;
}
catch (Exception ex) {
//Error logging to add
}
return retVal;
}
请有任何想法!
【问题讨论】:
-
不清楚你说什么。我发布了实际代码。我想说一些我无法打开的文件。
-
您的代码缺少 any 实际 write 到您的输出文件。所以说“它有时有效”是不正确的。
-
拥有空的
catch (Exception ex)块是愚蠢的。即使你用它做点什么,抓住一般的Exception已经够糟糕的了。你真的应该避免捕获这样的错误。 -
int Length = 1024 * 1024 * 30;也许这就是问题所在。拥有一个静态缓冲区似乎并不好。可能是缓冲区太小,因此文件没有完整写入。