C# ftp 下载代码,要可以选择下载目录的
展开全部
public 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 FtpUpDown(string ftpServerIP, string ftpUserID, string ftpPassword, int port) { this.ftpServerIP = ftpServerIP; this.ftpUserID = ftpUserID; this.ftpPassword = ftpPassword; } public 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.Default);//中文文件名 string line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = reader.ReadLine(); } // to remove the trailing '\n' result.Remove(result.ToString().LastIndexOf('\n'), 1); reader.Close(); response.Close(); return result.ToString().Split('\n'); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); downloadFiles = null; return downloadFiles; } } public string[] GetFileList(string path)//上面的代码示例了如何从ftp服务器上获得文件列表 { return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory); } public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表 { return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory); } public bool Download(string filePath, string fileName, string errorinfo, string saveName)////上面的代码实现了从ftp服务器下载文件的功能 { try { String onlyFileName = Path.GetFileName(saveName); string newFileName = filePath; if (File.Exists(newFileName)) { errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName); return false; } string url = "ftp://" + ftpServerIP + "/" + fileName; Connect(url);//连接 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); FileStream outputStream = new FileStream(newFileName, FileMode.Create); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); errorinfo = ""; return true; } catch (Exception ex) { errorinfo = string.Format("因{0},无法下载", ex.Message); return false; } }
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询