参见英文答案 Upload file and download file from FTP3个 作为初级开发人员,我应该找到一个使用ftp下载文件的解决方案,我有这个代码. 它工作但有时,我无法打开下载的文件. public static bool Downl
作为初级开发人员,我应该找到一个使用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;
}
有任何想法!
你为什么不用它? Microsoft已实施 WebClient从FTP下载.using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential("log", "pass");
client.DownloadFile("ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");
}
