日期:2014-05-18 浏览次数:21148 次
private void Download(string filePath, string fileName) { FtpWebRequest reqFTP; try { FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); long cl = response.ContentLength; int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
------解决方案--------------------
完整一点
public class FtpFile { string ftpServerIP; public string FtpServerIP { get { return ftpServerIP; } set { ftpServerIP = value; } } string ftpUserID; public string FtpUserID { get { return ftpUserID; } set { ftpUserID = value; } } string ftpPassword; public string FtpPassword { get { return ftpPassword; } set { ftpPassword = value; } } FtpWebRequest reqFTP; public static string FtpServer = System.Configuration.ConfigurationSettings.AppSettings["FtpServer"]; public static string FtpUser = System.Configuration.ConfigurationSettings.AppSettings["FtpUser"]; public static string FtpPwd = System.Configuration.ConfigurationSettings.AppSettings["FtpPwd"]; private void Connect(String path)//连接ftp { // 根据uri创建FtpWebRequest对象 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path)); // 指定数据传输类型 reqFTP.UseBinary = true; // ftp用户名和密码 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); } public FtpFile(string ftpServerIP, string ftpUserID, string ftpPassword) { this.ftpServerIP = ftpServerIP; this.ftpUserID = ftpUserID; this.ftpPassword = ftpPassword; } public FtpFile() { this.ftpServerIP = FtpServer; this.ftpUserID = FtpUser; this.ftpPassword = FtpPwd; }
------解决方案--------------------
//都调用这个 private string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表 { string[] downloadFiles; StringBuilder result = new StringBuilder(); try { Connect(path); reqFTP.Method = WRMethods; WebResponse response = reqFTP.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);//中文文件名 string line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append