public bool DownloadFile(string localFilePath, string ftpFilePath) { bool success = false; FtpWebRequest ftpWebRequest = null; FtpWebResponse ftpWebResponse = null; Stream ftpResponseStream = null; FileStream outputStream = null; try { string dir = Path.GetDirectoryName(localFilePath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (File.Exists(localFilePath)) { File.Delete(localFilePath); } ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpFilePath)); ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);//匿名的话,这里赋值为空 ftpWebRequest.UseBinary = true; ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile; ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse(); ftpResponseStream = ftpWebResponse.GetResponseStream(); long contentLength = ftpWebResponse.ContentLength; int bufferSize = 2048; byte[] buffer = new byte[bufferSize]; int readCount; readCount = ftpResponseStream.Read(buffer, 0, bufferSize); outputStream = new FileStream(localFilePath, FileMode.Create); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpResponseStream.Read(buffer, 0, bufferSize); } success = true; } catch (Exception e) { success = false; throw; } finally { if (outputStream != null) { outputStream.Close(); } if (ftpResponseStream != null) { ftpResponseStream.Close(); } if (ftpWebResponse != null) { ftpWebResponse.Close(); } } return success; }
Userid还是Password赋值为空?
@0ng_Ching_Tong: username和password都是空值
@Don'tWorryBeHappy: 你确定?我听人说 userid要填“ANONYMOUS“,密码不填?
@0ng_Ching_Tong: 我这边用都不用填,你可以试试
@Don'tWorryBeHappy: 好的 我试试先
直接下载整个文件下来,然后读取就可以了
wo也知道啊,代码怎么实现匿名下载ftp文件。。