第8章 FTP文件上传下载
详解ftp文件上传下载命令

详解ftp⽂件上传下载命令介绍:从本地以⽤户wasqry登录的机器1*.1**.21.67上通过ftp远程登录到ftp服务器上,登录⽤户名是lte****,以下为使⽤该连接做的实验。
查看远程ftp服务器上⽤户lte****相应⽬录下的⽂件所使⽤的命令为:ls,登录到ftp后在ftp命令提⽰符下查看本地机器⽤户wasqry相应⽬录下⽂件的命令是:!ls。
查询ftp命令可在提⽰符下输⼊:?,然后回车。
1、从远程ftp服务器下载⽂件的命令格式:get 远程ftp服务器上当前⽬录下要下载的⽂件名 [下载到本地机器上当前⽬录时的⽂件名],如:get nmap_file [nmap]意思是把远程ftp服务器下的⽂件nmap_file下载到本地机器的当前⽬录下,名称更改为nmap。
带括号表⽰可写可不写,不写的话是以该⽂件名下载。
如果要往ftp服务器上上传⽂件的话需要去修改⼀下vsftpd的配置⽂件,名称是vsftpd.conf,在/etc⽬录下。
要把其中的“#write_enable=YES”前⾯的“#”去掉并保存,然后重启vsftpd服务:sudo service vsftpd restart。
2、向远程ftp服务器上传⽂件的命令格式:put/mput 本地机器上当前⽬录下要上传的⽂件名 [上传到远程ftp服务器上当前⽬录时的⽂件名],如:put/mput sample.c [ftp_sample.c]意思是把本地机器当前⽬录下的⽂件smaple.c上传到远程ftp服务器的当前⽬录下,名称更改为ftp_sample.c。
带括号表⽰可写可不写,不写的话是以该⽂件名上传。
如图下download.sh等⽂件本位于该机器linux系统⽬录,通过如下命令,则将linux系统当前⽬录下的download.sh等⽂件上传⾄ftp服务器的当前⽬录3、最后附上ftp常⽤命令,如下所⽰:FTP>open [ftpservername],和指定的远程Linux FTP服务器连接?FTP>user [username] [password],使⽤指定远程Linux FTP服务器的⽤户登录?FTP>pwd,显⽰远程Linux FTP服务器上的当前路径?FTP>ls,列出远程Linux FTP服务器上当前路径下的⽬录和⽂件?FTP>dir,列出远程Linux FTP服务器上当前路径下的⽬录和⽂件(同上)?FTP>mkdir [foldname],在远程Linux FTP服务器上当前路径下建⽴指定⽬录?FTP>rmdir [foldname],删除远程Linux FTP服务器上当前路径下的指定⽬录?FTP>cd [foldname],更改远程Linux FTP服务器上的⼯作⽬录?FTP>delete [filename],删除远程Linux FTP服务器上指定的⽂件?FTP>rename [filename] [newfilename],重命名远程Linux FTP服务器上指定的⽂件?FTP>close,从远程Linux FTP服务器断开但保留FTP命令参数提⽰?FTP>disconnect,从远程Linux FTP服务器断开但保留FTP命令参数提⽰(同上)?FTP>bye,结束和远程Linux FTP服务器的连接。
8 internet 资源服务 2010

使用IE浏览Internet信息
• 使用导航按钮浏览
– – – – – “后退”按钮 “前进”按钮 “停止”按钮 “刷新”按钮 “主页”按钮
图8-6 导航按钮
8.2 电子邮件
• 电子邮件简介
– 用户发送和接收电子邮件的程序统称为用户代理 (UA)。在Internet中用户发送和接收电子邮件并不 像打电话那样直接与对方进行交换,而是类似日 常邮件通信的形式。因此,在Internet中设有类似 邮局的系统,这个系统叫做邮件传送代理(MTA)系 统。 – 邮件服务中的两个协议
IE浏览器的设置
标题栏 菜单栏 地址栏
• IE6.0窗口界面组成
常用工具栏 链接栏
浏览区
状态栏
图8-1 IE6.0窗口界面
IE浏览器的设置
• IE浏览器的界面设置
– 也许用户的IE浏览器 界面和上面所介绍的 有些不同,找不到其 中某个组件,或是布 局略有差异,这是由 “查看”命令设置造成的。 – 设置网页字体的大小 – 语言编码的设置
文件的下载与传输
• 使用迅雷下载软件
– 迅雷软件的下载与安装 (参考课本操作) – 迅雷软件的界面
– 任务分类说明
• • • • • • 任务管理窗口 更改默认的文件存放目录 向迅雷中添加下载任务 高级功能 完成后关机 查找
图8-24迅雷软件界面
文件的下载与传输
• 文件的传输
– FTP是File Transport Protocol的缩写,称为文件传 输协议。这一协议是专门用于在网络中传输文件 的。现在最流行的超文本传输协议HTTP也能够用 于传输文件,但是就传输文件的速度和稳定性来 讲,FTP都优于HTTP。这也就是说,用户在下载 过程中往往会发现一个文件可以通过很多URL来 下载。如果这些站点既有使用FTP(地址前是以 “ftp://”开头)的,也有使用HTTP(地址前是以 “http://”开头)的,最好就要选择FTP站点来下载。 – 使用FTP进行文件传输,包括两个方面: UpLoad(上传)和DownLoad(下载)。下载是从网络 服务器上将文件传送至本地计算机,上传正相反, 是由本地计算机向服务器端传输文件。
SFTP文件上传下载以及如何处理异常,页面展现

SFTP⽂件上传下载以及如何处理异常,页⾯展现⾸先需要⼀个第三⽅包,⽹上有很多种⽅式,我这⾥⽤的是ChannelSftpAPI地址 http://epaul.github.io/jsch-documentation/javadoc/com/jcraft/jsch/ChannelSftp.html1.⼯具类/**** @author Caicaizi**/public class SFTPUtils {private static final Logger LOG = LoggerFactory.getLogger(SFTPUtils.class);/*** 打开ssh会话** @param username* @param host* @param port* @param pwd* @return* @throws JSchException*/private static Session openSession(String username, String host, int port, String pwd) throws JSchException {JSch jsch = new JSch();Session session = jsch.getSession(username, host, port);session.setPassword(pwd);Properties config = new Properties();config.put("StrictHostKeyChecking", "no");config.put("PreferredAuthentications", "password");int timeout = 3000;session.setServerAliveInterval(timeout); //session.setConfig(config); // 为Session对象设置propertiessession.setTimeout(timeout); // 设置timeout时间session.connect(); // 通过Session建⽴连接("Session connected.");return session;}/*** 获取⽂件** @param filePath* ⽂件路径* @param out* 输出流* @param username* @param host* @param port* @param pwd*/public static void getFile(String filePath, OutputStream out, String username, String host, int port, String pwd) {ChannelSftp channel = null;Session session = null;try {session = openSession(username, host, port, pwd);("Opening channel");channel = (ChannelSftp) session.openChannel("sftp");channel.connect();channel.get(filePath, out);} catch (JSchException e) {LOG.error("连接服务器失败", e);} catch (SftpException e) {LOG.error("⽂件获取失败", e);} finally {close(channel, session);}}public static void uploadFile(InputStream input, String filename, String path, String username, String host,int port, String pwd) {ChannelSftp channel = null;Session session = null;try {session = openSession(username, host, port, pwd);channel = (ChannelSftp) session.openChannel("sftp");channel.connect();SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");String date = format.format(new Date());channel.cd(path);// 查看⽇期对应的⽬录状态try {channel.stat(date);} catch (Exception e) {("⽬录不存在,创建⽬录:" + path + "/" + date);channel.mkdir(date);}channel.put(input,path+"/"+date+"/"+filename);} catch (JSchException e) {LOG.error("连接服务器失败", e);} catch (SftpException e) {LOG.error("⽂件上传失败", e);} finally{close(channel, session);}}/*** 释放sftp连接资源** @param channel* @param session*/private static void close(ChannelSftp channel, Session session) {if (channel != null) {channel.quit();channel.disconnect();}if (session != null) {session.disconnect();}}} 我们所需要的参数必须:IP,PORT,路径,⽂件名,以及账号密码;上传⽂件可以直接调⽤:uploadFile,下载:getFile。
LeapFtp使用教程

LeapFtp可以说是一款功能强大的FTP软件,友好的用户界面,稳定的传输速度,拥有跟Netscape相仿的书签形式,连接更加方便。
支持断点续传功能,可以下载或上传整个目录,亦可直接删除整个目录,可让你设置队列一次下载或上传同一站点中不同目录下的文件,是南昌网站优化必备的软件,同时还具有不会因闲置过久而被远程FTP服务器踢出的功能。
并可直接编辑远端Server上的文件,还可设定文件传送完毕自动中断Modem连接等。
名词解释:【FTP】FTP是英文File Transfer Protocol的缩写,也就是文件传输协议的意思。
是TCP/IP 协议组中的协议之一,该协议是Internet文件传送的基础,它由一系列规格说明文档组成。
使得用户可以通过FTP功能登录到远程计算机,从其它计算机系统中下载需要的文件或将自己的文件上传到网络上。
第一:下载安装软件下载后为一个.exe格式的文件。
无需安装,可以直接双击运行。
第二:界面预览LeapFtp主界面默认显示了本地目录、远程目录、队列及状态四大窗口。
第三:站点设置要使用FTP工具来上传(下载)文件,首先必须要设定好FTP服务器的网址(IP地址)、授权访问的用户名及密码。
下面我们将演示具体的参数设置,看完之后即使是初入门的菜鸟级用户也能很快上手,哈哈。
通过菜单【站点】—>【站点管理器】或者F4键我们可以对要连接的远程FTP服务器进行具体的设置。
第一步:我们可以点击【添加站点】按钮,输入站点的名称(它只是对FTP站点的一个说明)。
第二步:按照界面所示,首先去掉匿名选项(匿名的意思就是不需要用户名和密码可以直接访问FTP服务器,但很多FTP服务器都禁止匿名访问),然后分别输入IP地址(FTP服务器所拥有的IP),用户名和密码(如果你不知道的话,可以询问提供FTP服务的运营商或管理员)。
另外对于端口号我们在没有特别要求的情况下就使用默认的端口号(21),不必在进行改变。
ftp文件操作类(上传、下载、删除、创建、重命名、获取目录中的所有文件)

ftp⽂件操作类(上传、下载、删除、创建、重命名、获取⽬录中的所有⽂件)ftp⽂件操作类1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using ;6using System.IO;7using System.Data;8using ponentModel;9using System.Windows.Forms;10using System.Text.RegularExpressions;11using System.Globalization;12using System.Collections;1314namespace ESIMRobot15 {16#region⽂件信息结构17public struct FileStruct18 {19public string Flags;20public string Owner;21public string Group;22public bool IsDirectory;23public DateTime CreateTime;24public string Name;25 }26public enum FileListStyle27 {28 UnixStyle,29 WindowsStyle,30 Unknown31 }32#endregion3334///<summary>35/// ftp⽂件上传、下载操作类36///</summary>37public class FTPHelper38 {39private string ftpServerURL;40private string ftpUser;41private string ftpPassWord;4243///<summary>44///45///</summary>46///<param name="ftpServerURL">ftp服务器路径</param>47///<param name="ftpUser">ftp⽤户名</param>48///<param name="ftpPassWord">ftp⽤户名</param>49public FTPHelper(string ftpServerURL, string ftpUser, string ftpPassWord)50 {51this.ftpServerURL = ftpServerURL;52this.ftpUser = ftpUser;53this.ftpPassWord = ftpPassWord;54 }55///<summary>56///通过⽤户名,密码连接到FTP服务器57///</summary>58///<param name="ftpUser">ftp⽤户名,匿名为“”</param>59///<param name="ftpPassWord">ftp登陆密码,匿名为“”</param>60public FTPHelper(string ftpUser, string ftpPassWord)61 {62this.ftpUser = ftpUser;63this.ftpPassWord = ftpPassWord;64 }6566///<summary>67///匿名访问68///</summary>69public FTPHelper(string ftpURL)70 {71this.ftpUser = "";72this.ftpPassWord = "";73 }747576//**************************************************** Start_1 *********************************************************//77///<summary>78///从FTP下载⽂件到本地服务器,⽀持断点下载79///</summary>80///<param name="ftpFilePath">ftp⽂件路径,如"ftp://localhost/test.txt"</param>81///<param name="saveFilePath">保存⽂件的路径,如C:\\test.txt</param>82public void BreakPointDownLoadFile(string ftpFilePath, string saveFilePath)83 {84 System.IO.FileStream fs = null;85 .FtpWebResponse ftpRes = null;86 System.IO.Stream resStrm = null;87try88 {89//下载⽂件的URI90 Uri uri = new Uri(ftpFilePath);91//设定下载⽂件的保存路径92string downFile = saveFilePath;9394//FtpWebRequest的作成95 .FtpWebRequest ftpReq = (.FtpWebRequest)96 .WebRequest.Create(uri);97//设定⽤户名和密码98 ftpReq.Credentials = new workCredential(ftpUser, ftpPassWord);99//MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定100 ftpReq.Method = .WebRequestMethods.Ftp.DownloadFile;101//要求终了后关闭连接102 ftpReq.KeepAlive = false;103//使⽤ASCII⽅式传送104 eBinary = false;105//设定PASSIVE⽅式⽆效106 ePassive = false;107108//判断是否继续下载109//继续写⼊下载⽂件的FileStream110if (System.IO.File.Exists(downFile))111 {112//继续下载113 ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length;114 fs = new System.IO.FileStream(115 downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write);116 }117else118 {119//⼀般下载120 fs = new System.IO.FileStream(121 downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);122 }123124//取得FtpWebResponse125 ftpRes = (.FtpWebResponse)ftpReq.GetResponse();126//为了下载⽂件取得Stream127 resStrm = ftpRes.GetResponseStream();128//写⼊下载的数据129byte[] buffer = new byte[1024];130while (true)131 {132int readSize = resStrm.Read(buffer, 0, buffer.Length);133if (readSize == 0)134break;135 fs.Write(buffer, 0, readSize);136 }137 }138catch (Exception ex)139 {140throw new Exception("从ftp服务器下载⽂件出错,⽂件名:" + ftpFilePath + "异常信息:" + ex.ToString()); 141 }142finally143 {144 fs.Close();145 resStrm.Close();146 ftpRes.Close();147 }148 }149150151#region152//从FTP上下载整个⽂件夹,包括⽂件夹下的⽂件和⽂件夹函数列表153154///<summary>155///从ftp下载⽂件到本地服务器156///</summary>157///<param name="ftpFilePath">要下载的ftp⽂件路径,如ftp://192.168.1.104/capture-2.avi</param>158///<param name="saveFilePath">本地保存⽂件的路径,如(@"d:\capture-22.avi"</param>159public void DownLoadFile(string ftpFilePath, string saveFilePath)160 {161 Stream responseStream = null;162 FileStream fileStream = null;163 StreamReader reader = null;164try165 {166// string downloadUrl = "ftp://192.168.1.104/capture-2.avi";167 FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(ftpFilePath);168 downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;169 downloadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);170 FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse();171 responseStream = downloadResponse.GetResponseStream();172173 fileStream = File.Create(saveFilePath);174byte[] buffer = new byte[1024];175int bytesRead;176while (true)177 {178 bytesRead = responseStream.Read(buffer, 0, buffer.Length);179if (bytesRead == 0)180break;181 fileStream.Write(buffer, 0, bytesRead);182 }183 }184catch (Exception ex)185 {186throw new Exception("从ftp服务器下载⽂件出错,⽂件名:" + ftpFilePath + "异常信息:" + ex.ToString()); 187 }188finally189 {190if (reader != null)191 {192 reader.Close();193 }194if (responseStream != null)195 {196 responseStream.Close();197 }198if (fileStream != null)199 {200 fileStream.Close();201 }202 }203 }204205206///<summary>207///列出当前⽬录下的所有⽂件和⽬录208///</summary>209///<param name="ftpDirPath">FTP⽬录</param>210///<returns></returns>211public List<FileStruct> ListCurrentDirFilesAndChildDirs(string ftpDirPath)212 {213 WebResponse webresp = null;214 StreamReader ftpFileListReader = null;215 FtpWebRequest ftpRequest = null;216try217 {218 ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpDirPath));219 ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;220 ftpRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);221 webresp = ftpRequest.GetResponse();222 ftpFileListReader = new StreamReader(webresp.GetResponseStream(),Encoding.GetEncoding("UTF-8")); 223 }224catch (Exception ex)225 {226throw new Exception("获取⽂件列表出错,错误信息如下:" + ex.ToString());227 }228string Datastring = ftpFileListReader.ReadToEnd();229return GetListX(Datastring);230231 }232233///<summary>234///列出当前⽬录下的所有⽂件235///</summary>236///<param name="ftpDirPath">FTP⽬录</param>237///<returns></returns>238public List<FileStruct> ListCurrentDirFiles(string ftpDirPath)239 {240 List<FileStruct> listAll = ListCurrentDirFilesAndChildDirs(ftpDirPath);241 List<FileStruct> listFile = new List<FileStruct>();242foreach (FileStruct file in listAll)243 {244if (!file.IsDirectory)245 {246 listFile.Add(file);247 }248 }249return listFile;250 }251252253///<summary>254///列出当前⽬录下的所有⼦⽬录255///</summary>256///<param name="ftpDirath">FRTP⽬录</param>257///<returns>⽬录列表</returns>258public List<FileStruct> ListCurrentDirChildDirs(string ftpDirath)259 {260 List<FileStruct> listAll = ListCurrentDirFilesAndChildDirs(ftpDirath);261 List<FileStruct> listDirectory = new List<FileStruct>();262foreach (FileStruct file in listAll)263 {264if (file.IsDirectory)265 {266 listDirectory.Add(file);267 }268 }269return listDirectory;270 }271272273///<summary>274///获得⽂件和⽬录列表(返回类型为: List<FileStruct> )275///</summary>276///<param name="datastring">FTP返回的列表字符信息</param>277private List<FileStruct> GetListX(string datastring)278 {279 List<FileStruct> myListArray = new List<FileStruct>();280string[] dataRecords = datastring.Split('\n');281 FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);282foreach (string s in dataRecords)283 {284if (_directoryListStyle != FileListStyle.Unknown && s != "")285 {286 FileStruct f = new FileStruct();287 = "..";288switch (_directoryListStyle)289 {290case FileListStyle.UnixStyle:291 f = ParseFileStructFromUnixStyleRecord(s);292break;293case FileListStyle.WindowsStyle:294 f = ParseFileStructFromWindowsStyleRecord(s);295break;296 }297if (!( == "." || == ".."))298 {299 myListArray.Add(f);300 }301 }302 }303return myListArray;304 }305///<summary>306///从Unix格式中返回⽂件信息307///</summary>308///<param name="Record">⽂件信息</param>309private FileStruct ParseFileStructFromUnixStyleRecord(string Record)310 {311 FileStruct f = new FileStruct();312string processstr = Record.Trim();313 f.Flags = processstr.Substring(0, 10);314 f.IsDirectory = (f.Flags[0] == 'd');315 processstr = (processstr.Substring(11)).Trim();316 cutSubstringFromStringWithTrim(ref processstr, '', 0); //跳过⼀部分317 f.Owner = cutSubstringFromStringWithTrim(ref processstr, '', 0);318 f.Group = cutSubstringFromStringWithTrim(ref processstr, '', 0);319 cutSubstringFromStringWithTrim(ref processstr, '', 0); //跳过⼀部分320string yearOrTime = processstr.Split(new char[] { '' }, StringSplitOptions.RemoveEmptyEntries)[2]; 321if (yearOrTime.IndexOf(":") >= 0) //time322 {323 processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());324 }325 f.CreateTime = DateTime.Parse(cutSubstringFromStringWithTrim(ref processstr, '', 8));326 = processstr; //最后就是名称327return f;328 }329330///<summary>331///从Windows格式中返回⽂件信息332///</summary>333///<param name="Record">⽂件信息</param>334private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)335 {336 FileStruct f = new FileStruct();337string processstr = Record.Trim();338string dateStr = processstr.Substring(0, 8);339 processstr = (processstr.Substring(8, processstr.Length - 8)).Trim();340string timeStr = processstr.Substring(0, 7);341 processstr = (processstr.Substring(7, processstr.Length - 7)).Trim();342 DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;343 myDTFI.ShortTimePattern = "t";344 f.CreateTime = DateTime.Parse(dateStr + "" + timeStr, myDTFI);345if (processstr.Substring(0, 5) == "<DIR>")346 {347 f.IsDirectory = true;348 processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();349 }350else351 {352string[] strs = processstr.Split(new char[] { '' }, 2);// StringSplitOptions.RemoveEmptyEntries); // true); 353 processstr = strs[1];354 f.IsDirectory = false;355 }356 = processstr;357return f;358 }359360361///<summary>362///按照⼀定的规则进⾏字符串截取363///</summary>364///<param name="s">截取的字符串</param>365///<param name="c">查找的字符</param>366///<param name="startIndex">查找的位置</param>367private string cutSubstringFromStringWithTrim(ref string s, char c, int startIndex)368 {369int pos1 = s.IndexOf(c, startIndex);370string retString = s.Substring(0, pos1);371 s = (s.Substring(pos1)).Trim();372return retString;373 }374375376///<summary>377///判断⽂件列表的⽅式Window⽅式还是Unix⽅式378///</summary>379///<param name="recordList">⽂件信息列表</param>380private FileListStyle GuessFileListStyle(string[] recordList)381 {382foreach (string s in recordList)383 {384if (s.Length > 10385 && Regex.IsMatch(s.Substring(0, 10), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)"))386 {387return FileListStyle.UnixStyle;388 }389else if (s.Length > 8390 && Regex.IsMatch(s.Substring(0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"))391 {392return FileListStyle.WindowsStyle;393 }394 }395return FileListStyle.Unknown;396 }397398399///<summary>400///从FTP下载整个⽂件夹401///</summary>402///<param name="ftpDirPath">FTP⽂件夹路径</param>403///<param name="saveDirPath">保存的本地⽂件夹路径</param>404///调⽤实例: DownFtpDir("FTP://192.168.1.113/WangJin", @"C:\QMDownload\SoftMgr");405///当调⽤的时候先判断saveDirPath的⼦⽬录中是否有WangJin⽬录,有则执⾏,没有创建后执⾏406///最终⽂件保存在@"C:\QMDownload\SoftMgr\WangJin"下407public bool DownFtpDir(string ftpDirPath, string saveDirPath)408 {409bool success = true;410try411 {412 List<FileStruct> files = ListCurrentDirFilesAndChildDirs(ftpDirPath);413if (!Directory.Exists(saveDirPath))414 {415 Directory.CreateDirectory(saveDirPath);416 }417foreach (FileStruct f in files)418 {419if (f.IsDirectory) //⽂件夹,递归查询421 DownFtpDir(ftpDirPath + "/" + , saveDirPath + "\\" + );422 }423else//⽂件,直接下载424 {425 DownLoadFile(ftpDirPath + "/" + , saveDirPath + "\\" + );426 }427 }428 }429catch (Exception e)430 {431 MessageBox.Show(e.Message);432 success = false;433 }434return success;435 }436#endregion437438439440///<summary>441///列出当前⽬录下的所有⼦⽬录和⽂件到TreeView控件中442///</summary>443///<param name="ftpDirPath"> FTP服务器⽬录</param>444///<param name="treeview">显⽰到TreeView控件中</param>445///<param name="treenode">TreeView控件的⼦节点</param>446public void ListCurrentDirFilesAndDirToTreeView(string ftpDirPath, TreeView treeview, TreeNode treenode) 447 {448if (ftpDirPath == "")449 {450 ftpDirPath = ftpServerURL;451 }452if (treeview != null)453 {454 treeview.Nodes.Clear();455 treenode = treeview.Nodes.Add(ftpDirPath);456 }457 List<FileStruct> files = ListCurrentDirFilesAndChildDirs(ftpDirPath);458foreach (FileStruct f in files)459 {460if (f.IsDirectory) //如果为⽬录(⽂件夹),递归调⽤461 {462 TreeNode td = treenode.Nodes.Add();463 ListCurrentDirFilesAndDirToTreeView(ftpDirPath + "/" + , null, td);464 }465else//如果为⽂件,直接加⼊到节点中466 {467 treenode.Nodes.Add();468 }469 }470 }471//************************************* End_1 ****************************//472473474475476//************************************ Start_2 ***************************//477///<summary>478///检测⽂件或⽂件⽬录是否存在479///</summary>480///<param name="ftpDirPath">ftp服务器中的⽬录路径</param>481///<param name="ftpDirORFileName">待检测的⽂件或⽂件名</param>482///<returns></returns>483///操作实例: ftpclient.fileOrDirCheckExist("FTP://192.168.1.113/Record/", "")484/// ftpclient.fileOrDirCheckExist("FTP://192.168.1.113/RecordFile/", "333.txt")485public bool fileOrDirCheckExist(string ftpDirPath, string ftpDirORFileName)486 {487bool success = true;488 FtpWebRequest ftpWebRequest = null;489 WebResponse webResponse = null;490 StreamReader reader = null;491try492 {493string url = ftpDirPath + ftpDirORFileName;494 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));495 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);496 ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;497 ftpWebRequest.KeepAlive = false;498 webResponse = ftpWebRequest.GetResponse();499 reader = new StreamReader(webResponse.GetResponseStream());500string line = reader.ReadLine();501while (line != null)502 {503if (line == ftpDirORFileName)504 {505break;507 line = reader.ReadLine();508 }509 }510catch (Exception)511 {512 success = false;513 }514finally515 {516if (reader != null)517 {518 reader.Close();519 }520if (webResponse != null)521 {522 webResponse.Close();523 }524 }525return success;526 }527528529///<summary>530///获得⽂件和⽬录列表(返回类型为:FileStruct)531///</summary>532///<param name="datastring">FTP返回的列表字符信息</param>533public FileStruct GetList(string datastring)534 {535 FileStruct f = new FileStruct();536string[] dataRecords = datastring.Split('\n');537 FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);538if (_directoryListStyle != FileListStyle.Unknown && datastring != "")539 {540541switch (_directoryListStyle)542 {543case FileListStyle.UnixStyle:544 f = ParseFileStructFromUnixStyleRecord(datastring);545break;546case FileListStyle.WindowsStyle:547 f = ParseFileStructFromWindowsStyleRecord(datastring);548break;549 }550 }551return f;552 }553554555///<summary>556///上传557///</summary>558///<param name="localFilePath">本地⽂件名路径</param>559///<param name="ftpDirPath">上传到ftp中⽬录的路径</param>560///<param name="ftpFileName">上传到ftp中⽬录的⽂件名</param>561///<param name="fileLength">限制上传⽂件的⼤⼩(Bytes为单位)</param>562///操作实例: ftpclient.fileUpload(@"E:\bin\Debug\Web\RecordFile\wangjin\wangjin.txt", "FTP://192.168.1.113/Record/","123.txt",0 );563public bool UploadFile(FileInfo localFilePath, string ftpDirPath, string ftpFileName, long fileLength)564 {565bool success = true;566long filesize = 0;567 FtpWebRequest ftpWebRequest = null;568 FileStream localFileStream = null;569 Stream requestStream = null;570if (fileLength > 0)571 {572 filesize = fileLength * 1024 * 1024;573 }574if (localFilePath.Length <= filesize || filesize == 0)575 {576if (fileOrDirCheckExist(ftpDirPath.Substring(0, stIndexOf(@"/") + 1), ftpDirPath.Substring(stIndexOf(@"/") + 1))) 577 {578try579 {580string uri = ftpDirPath + ftpFileName;581 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));582 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);583 eBinary = true;584 ftpWebRequest.KeepAlive = false;585 ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;586 ftpWebRequest.ContentLength = localFilePath.Length;587int buffLength = 2048; //定义缓存⼤⼩2KB588byte[] buff = new byte[buffLength];589int contentLen;590 localFileStream = localFilePath.OpenRead();591 requestStream = ftpWebRequest.GetRequestStream();592 contentLen = localFileStream.Read(buff, 0, buffLength);593while (contentLen != 0)594 {595 requestStream.Write(buff, 0, contentLen);596 contentLen = localFileStream.Read(buff, 0, buffLength);597 }598 }599catch (Exception)600 {601 success = false;602 }603finally604 {605if (requestStream != null)606 {607 requestStream.Close();608 }609if (localFileStream != null)610 {611 localFileStream.Close();612 }613 }614 }615else616 {617 success = false;618 MessageBox.Show("FTP⽂件路径不存在!");619 }620 }621else622 {623 success = false;624 MessageBox.Show("⽂件⼤⼩超过设置范围!" + "\n" + "⽂件实际⼤⼩为:" + localFilePath.Length + "\n" + "允许上传阈值为:" + (5 * 1024 * 1024).ToString()); 625 }626return success;627 }628629///<summary>630///下载⽂件631///</summary>632///<param name="ftpFilePath">需要下载的⽂件名路径</param>633///<param name="localFilePath">本地保存的⽂件名路径)</param>634///操作实例: ftpclient.fileDownload(@"E:\bin\Debug\Web\RecordFile\wangjin\459.txt", "FTP://192.168.1.113/Record/123.txt");635public bool DownloadFile( string localFilePath, string ftpFilePath)636 {637bool success = true;638 FtpWebRequest ftpWebRequest = null;639 FtpWebResponse ftpWebResponse = null;640 Stream ftpResponseStream = null;641 FileStream outputStream = null;642try643 {644 outputStream = new FileStream(localFilePath, FileMode.Create);645string uri = ftpFilePath;646 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));647 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);648 eBinary = true;649 ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;650 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();651 ftpResponseStream = ftpWebResponse.GetResponseStream();652long contentLength = ftpWebResponse.ContentLength;653int bufferSize = 2048;654byte[] buffer = new byte[bufferSize];655int readCount;656 readCount = ftpResponseStream.Read(buffer, 0, bufferSize);657while (readCount > 0)658 {659 outputStream.Write(buffer, 0, readCount);660 readCount = ftpResponseStream.Read(buffer, 0, bufferSize);661 }662 }663catch (Exception)664 {665 success = false;666 }667finally668 {669if (outputStream != null)670 {671 outputStream.Close();672 }673if (ftpResponseStream != null)674 {675 ftpResponseStream.Close();676 }677if (ftpWebResponse != null)679 ftpWebResponse.Close();680 }681 }682return success;683 }684685686///<summary>687///重命名688///</summary>689///<param name="ftpDirPath">ftp服务器中的⽬录</param>690///<param name="currentFilename">当前要修改的⽂件名</param>691///<param name="newFilename">修改后的新⽂件名</param>692///操作实例: ftpclientxy.fileRename("FTP://192.168.1.113/RecordFile/", "123.txt", "333.txt");693public bool RenameFile(string ftpDirPath, string currentFileName, string newFileName)694 {695bool success = true;696 FtpWebRequest ftpWebRequest = null;697 FtpWebResponse ftpWebResponse = null;698 Stream ftpResponseStream = null;699if (fileOrDirCheckExist(ftpDirPath.Substring(0, stIndexOf(@"/") + 1), ftpDirPath.Substring(stIndexOf(@"/") + 1))) 700 {701try702 {703string uri = ftpDirPath + currentFileName;704 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));705 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);706 eBinary = true;707 ftpWebRequest.Method = WebRequestMethods.Ftp.Rename;708 ftpWebRequest.RenameTo = newFileName;709 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();710 ftpResponseStream = ftpWebResponse.GetResponseStream();711 }712catch (Exception)713 {714 success = false;715 }716finally717 {718if (ftpResponseStream != null)719 {720 ftpResponseStream.Close();721 }722if (ftpWebResponse != null)723 {724 ftpWebResponse.Close();725 }726 }727 }728else729 {730 success = false;731 MessageBox.Show("FTP⽂件路径不存在!");732 }733return success;734 }735736///<summary>737///在⽬录下创建⼦⽬录738///</summary>739///<param name="ftpDirPath">ftp服务器中的⽬录</param>740///<param name="ftpFileDir">待创建的⼦⽬录</param>741///<returns></returns>742///操作实例: ftpclient.fileDirMake("FTP://192.168.1.113/RecordFile/", "WangJinFile")743public bool MakeDir(string ftpDirPath, string ftpFileDir)744 {745bool success = true;746 FtpWebRequest ftpWebRequest = null;747 WebResponse webResponse = null;748 StreamReader reader = null;749try750 {751string url = ftpDirPath + ftpFileDir;752 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));753// 指定数据传输类型754 eBinary = true;755 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);756 ftpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory;757 webResponse = ftpWebRequest.GetResponse();758 }759catch (Exception)760 {761 success = false;762 }763finally765if (reader != null)766 {767 reader.Close();768 }769if (webResponse != null)770 {771 webResponse.Close();772 }773 }774return success;775 }776777778///<summary>779///删除⽬录中的⽂件780///</summary>781///<param name="ftpDirPath"></param>782///<param name="ftpFileName"></param>783///<returns></returns>784///操作实例: ftpclient.fileDelete("FTP://192.168.1.113/RecordFile/WangJinFile/", "333.txt")785public bool DeleteFile(string ftpDirPath, string ftpFileName)786 {787bool success = true;788 FtpWebRequest ftpWebRequest = null;789 FtpWebResponse ftpWebResponse = null;790 Stream ftpResponseStream = null;791 StreamReader streamReader = null;792try793 {794string uri = ftpDirPath + ftpFileName;795 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));796 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);797 ftpWebRequest.KeepAlive = false;798 ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile;799 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();800long size = ftpWebResponse.ContentLength;801 ftpResponseStream = ftpWebResponse.GetResponseStream();802 streamReader = new StreamReader(ftpResponseStream);803string result = String.Empty;804 result = streamReader.ReadToEnd();805 }806catch (Exception)807 {808 success = false;809 }810finally811 {812if (streamReader != null)813 {814 streamReader.Close();815 }816if (ftpResponseStream != null)817 {818 ftpResponseStream.Close();819 }820if (ftpWebResponse != null)821 {822 ftpWebResponse.Close();823 }824 }825return success;826 }827828///<summary>829///获取⽬录的⼦⽬录数组830///</summary>831///<param name="ftpDirPath"></param>832///<returns></returns>833///操作实例: string []filedir = ftpclient.GetDeleteFolderArray("FTP://192.168.1.113/WangJinFile/"); 834public string[] GetDirArray(string ftpDirPath)835 {836string[] deleteFolders;837 FtpWebRequest ftpWebRequest = null;838 FtpWebResponse ftpWebResponse = null;839 Stream ftpResponseStream = null;840 StreamReader streamReader = null;841 StringBuilder result = new StringBuilder();842try843 {844 ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpDirPath));845 eBinary = true;846 ePassive = false;847 ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);848 ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;849 ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();。
FTP文件传输

6.6 FTP的节点资源 FTP的节点资源
请同学对感兴趣tAnts使用界面
24
网络蚂蚁具有以下特点:
(1)支持HTTP和FTP协议 (2)用户可随时中止正在下载的任务,任务将自动保存当前 状态,并在下次开始时,在当前状态下继续。 (3)支持OLE拖放,用户可从浏览器中将链接拖入任务列表 (4)裁剪板自动监视,并可指定将捕获的文件类型。 (5)捕获浏览器的动作,当用户在浏览器中单击链接时,网 络蚂蚁将自动激活 (6) 支持代理服务器。 (7)自动拨号,自动断线,自动关机。 (8)手动限速,自动限速。
7
(6)服务器“控制进程”创建“数据传送 进程”,并通过端口20与客户端建立“数 据传输连接” ; (7)客户端通过建立的“控制连接”传送 交互命令,通过“数据连接”接收服务器 传来的文件数据; (8)传输结束,服务器端释放“数据连 接”,“数据传输进程”自动终止; (9)客户端输入退出命令,释放“控制连 接” ; (10)服务器端“控制进程”自动终止。 至此整个FTP会话过程结束。
9
⑴ ftp ⑵ Connected to ⑶ 220 FTP server(version wu2.6.1) ready. ⑷ User(:(none)):anonymous ⑸ 331 Guest login ok,send your complete e-mail address as password. ⑹ Password:abc@ ⑺ 230 Guest login ok,access restrictions apply. ⑻ ftp> cd rfc ⑼ 250 CWD command successful. ⑽ ftp>get rfc2107.txt abc.txt ⑾ 200 port command successful. 150 opening ASCII ⑿ rfc2107.txt(44300 bytes) ⒀ 226 Transfer complete. ⒁ ftp: 45479 bytes received in 0.50seconds 90.96kbytes/sec. ⒂ ftp>bye ⒃ 221 Goodbye.
C#-FTP递归下载文件

C#-FTP递归下载⽂件c# ftp递归下载⽂件,找来找去这个最好。
(打断点,⼀⼩处foreach要改成for)///<summary>/// ftp⽂件上传、下载操作类///</summary>public class FTPHelper{///<summary>/// ftp⽤户名,匿名为“”///</summary>private string ftpUser;///<summary>/// ftp⽤户密码,匿名为“”///</summary>private string ftpPassWord;///<summary>///通过⽤户名,密码连接到FTP服务器///</summary>///<param name="ftpUser">ftp⽤户名,匿名为“”</param>///<param name="ftpPassWord">ftp登陆密码,匿名为“”</param>public FTPHelper(string ftpUser, string ftpPassWord){this.ftpUser = ftpUser;this.ftpPassWord = ftpPassWord;}///<summary>///匿名访问///</summary>public FTPHelper(){this.ftpUser = "";this.ftpPassWord = "";}///<summary>///上传⽂件到Ftp服务器///</summary>///<param name="uri">把上传的⽂件保存为ftp服务器⽂件的uri,如"ftp://192.168.1.104/capture-212.avi"</param> ///<param name="upLoadFile">要上传的本地的⽂件路径,如D:\capture-2.avi</param>public void UpLoadFile(string UpLoadUri, string upLoadFile){Stream requestStream = null;FileStream fileStream = null;FtpWebResponse uploadResponse = null;try{Uri uri = new Uri(UpLoadUri);FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uri);uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;uploadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);requestStream = uploadRequest.GetRequestStream();fileStream = File.Open(upLoadFile, FileMode.Open);byte[] buffer = new byte[1024];int bytesRead;while (true){bytesRead = fileStream.Read(buffer, 0, buffer.Length);if (bytesRead == 0)break;requestStream.Write(buffer, 0, bytesRead);}requestStream.Close();uploadResponse = (FtpWebResponse)uploadRequest.GetResponse();}catch (Exception ex){throw new Exception("上传⽂件到ftp服务器出错,⽂件名:" + upLoadFile + "异常信息:" + ex.ToString()); }finally{if (uploadResponse != null)uploadResponse.Close();if (fileStream != null)fileStream.Close();if (requestStream != null)requestStream.Close();}}///<summary>///从ftp下载⽂件到本地服务器///</summary>///<param name="downloadUrl">要下载的ftp⽂件路径,如ftp://192.168.1.104/capture-2.avi</param>///<param name="saveFileUrl">本地保存⽂件的路径,如(@"d:\capture-22.avi"</param>public void DownLoadFile(string downloadUrl, string saveFileUrl){Stream responseStream = null;FileStream fileStream = null;StreamReader reader = null;try{// string downloadUrl = "ftp://192.168.1.104/capture-2.avi";FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(downloadUrl);downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;//string ftpUser = "yoyo";//string ftpPassWord = "123456";downloadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse();responseStream = downloadResponse.GetResponseStream();fileStream = File.Create(saveFileUrl);byte[] buffer = new byte[1024];int bytesRead;while (true){bytesRead = responseStream.Read(buffer, 0, buffer.Length);if (bytesRead == 0)break;fileStream.Write(buffer, 0, bytesRead);}}catch (Exception ex){throw new Exception("从ftp服务器下载⽂件出错,⽂件名:" + downloadUrl + "异常信息:" + ex.ToString()); }finally{if (reader != null){reader.Close();}if (responseStream != null){responseStream.Close();}if (fileStream != null){fileStream.Close();}}}///<summary>///从FTP下载⽂件到本地服务器,⽀持断点下载///</summary>///<param name="ftpUri">ftp⽂件路径,如"ftp://localhost/test.txt"</param>///<param name="saveFile">保存⽂件的路径,如C:\\test.txt</param>public void BreakPointDownLoadFile(string ftpUri, string saveFile){System.IO.FileStream fs = null;.FtpWebResponse ftpRes = null;System.IO.Stream resStrm = null;try{//下载⽂件的URIUri u = new Uri(ftpUri);//设定下载⽂件的保存路径string downFile = saveFile;//FtpWebRequest的作成.FtpWebRequest ftpReq = (.FtpWebRequest).WebRequest.Create(u);//设定⽤户名和密码ftpReq.Credentials = new workCredential(ftpUser, ftpPassWord);//MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定ftpReq.Method = .WebRequestMethods.Ftp.DownloadFile;//要求终了后关闭连接ftpReq.KeepAlive = false;//使⽤ASCII⽅式传送eBinary = false;//设定PASSIVE⽅式⽆效ePassive = false;//判断是否继续下载//继续写⼊下载⽂件的FileStreamif (System.IO.File.Exists(downFile)){//继续下载ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length;fs = new System.IO.FileStream(downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write);}else{//⼀般下载fs = new System.IO.FileStream(downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);}//取得FtpWebResponseftpRes = (.FtpWebResponse)ftpReq.GetResponse();//为了下载⽂件取得StreamresStrm = ftpRes.GetResponseStream();//写⼊下载的数据byte[] buffer = new byte[1024];while (true){int readSize = resStrm.Read(buffer, 0, buffer.Length);if (readSize == 0)break;fs.Write(buffer, 0, readSize);}}catch (Exception ex){throw new Exception("从ftp服务器下载⽂件出错,⽂件名:" + ftpUri + "异常信息:" + ex.ToString()); }finally{fs.Close();resStrm.Close();ftpRes.Close();}}#region从FTP上下载整个⽂件夹,包括⽂件夹下的⽂件和⽂件夹///<summary>///列出FTP服务器上⾯当前⽬录的所有⽂件和⽬录///</summary>///<param name="ftpUri">FTP⽬录</param>///<returns></returns>public List<FileStruct> ListFilesAndDirectories(string ftpUri){WebResponse webresp = null;StreamReader ftpFileListReader = null;FtpWebRequest ftpRequest = null;try{ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpUri));ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;ftpRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);webresp = ftpRequest.GetResponse();ftpFileListReader = new StreamReader(webresp.GetResponseStream(), Encoding.Default);}catch (Exception ex){throw new Exception("获取⽂件列表出错,错误信息如下:" + ex.ToString());}string Datastring = ftpFileListReader.ReadToEnd();return GetList(Datastring);}///<summary>///列出FTP⽬录下的所有⽂件///</summary>///<param name="ftpUri">FTP⽬录</param>///<returns></returns>public List<FileStruct> ListFiles(string ftpUri){List<FileStruct> listAll = ListFilesAndDirectories(ftpUri);List<FileStruct> listFile = new List<FileStruct>();foreach (FileStruct file in listAll){if (!file.IsDirectory){listFile.Add(file);}}return listFile;}///<summary>///列出FTP⽬录下的所有⽬录///</summary>///<param name="ftpUri">FRTP⽬录</param>///<returns>⽬录列表</returns>public List<FileStruct> ListDirectories(string ftpUri){List<FileStruct> listAll = ListFilesAndDirectories(ftpUri);List<FileStruct> listDirectory = new List<FileStruct>();foreach (FileStruct file in listAll){if (file.IsDirectory){listDirectory.Add(file);}}return listDirectory;}///<summary>///获得⽂件和⽬录列表///</summary>///<param name="datastring">FTP返回的列表字符信息</param>private List<FileStruct> GetList(string datastring){List<FileStruct> myListArray = new List<FileStruct>();string[] dataRecords = datastring.Split('\n');FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);foreach (string s in dataRecords){if (_directoryListStyle != FileListStyle.Unknown && s != ""){FileStruct f = new FileStruct(); = "..";switch (_directoryListStyle){case FileListStyle.UnixStyle:f = ParseFileStructFromUnixStyleRecord(s);break;case FileListStyle.WindowsStyle:f = ParseFileStructFromWindowsStyleRecord(s);break;}if (!( == "." || == "..")){myListArray.Add(f);}}}return myListArray;}///<summary>///从Unix格式中返回⽂件信息///</summary>///<param name="Record">⽂件信息</param>private FileStruct ParseFileStructFromUnixStyleRecord(string Record) {FileStruct f = new FileStruct();string processstr = Record.Trim();f.Flags = processstr.Substring(0, 10);f.IsDirectory = (f.Flags[0] == 'd');processstr = (processstr.Substring(11)).Trim();_cutSubstringFromStringWithTrim(ref processstr, '', 0); //跳过⼀部分f.Owner = _cutSubstringFromStringWithTrim(ref processstr, '', 0);f.Group = _cutSubstringFromStringWithTrim(ref processstr, '', 0);_cutSubstringFromStringWithTrim(ref processstr, '', 0); //跳过⼀部分string yearOrTime = processstr.Split(new char[] { '' }, StringSplitOptions.RemoveEmptyEntries)[2];if (yearOrTime.IndexOf(":") >= 0) //time{processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());}f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, '', 8)); = processstr; //最后就是名称return f;}///<summary>///从Windows格式中返回⽂件信息///</summary>///<param name="Record">⽂件信息</param>private FileStruct ParseFileStructFromWindowsStyleRecord(string Record){FileStruct f = new FileStruct();string processstr = Record.Trim();string dateStr = processstr.Substring(0, 8);processstr = (processstr.Substring(8, processstr.Length - 8)).Trim();string timeStr = processstr.Substring(0, 7);processstr = (processstr.Substring(7, processstr.Length - 7)).Trim();DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;myDTFI.ShortTimePattern = "t";f.CreateTime = DateTime.Parse(dateStr + "" + timeStr, myDTFI);if (processstr.Substring(0, 5) == "<DIR>"){f.IsDirectory = true;processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();}else{string[] strs = processstr.Split(new char[] { '' },2);// StringSplitOptions.RemoveEmptyEntries); // true); processstr = strs[1];f.IsDirectory = false;} = processstr;return f;}///<summary>///按照⼀定的规则进⾏字符串截取///</summary>///<param name="s">截取的字符串</param>///<param name="c">查找的字符</param>///<param name="startIndex">查找的位置</param>private string _cutSubstringFromStringWithTrim(ref string s, char c, int startIndex){int pos1 = s.IndexOf(c, startIndex);string retString = s.Substring(0, pos1);s = (s.Substring(pos1)).Trim();return retString;}///<summary>///判断⽂件列表的⽅式Window⽅式还是Unix⽅式///</summary>///<param name="recordList">⽂件信息列表</param>private FileListStyle GuessFileListStyle(string[] recordList){foreach (string s in recordList){if (s.Length > 10&& Regex.IsMatch(s.Substring(0, 10), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)")){return FileListStyle.UnixStyle;}else if (s.Length > 8&& Regex.IsMatch(s.Substring(0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]")){return FileListStyle.WindowsStyle;}}return FileListStyle.Unknown;}///<summary>///从FTP下载整个⽂件夹///</summary>///<param name="ftpDir">FTP⽂件夹路径</param>///<param name="saveDir">保存的本地⽂件夹路径</param>public void DownFtpDir(string ftpDir, string saveDir){List<FileStruct> files = ListFilesAndDirectories(ftpDir);if (!Directory.Exists(saveDir)){Directory.CreateDirectory(saveDir);}foreach (FileStruct f in files){if (f.IsDirectory) //⽂件夹,递归查询{DownFtpDir(ftpDir + "/" + , saveDir + "\\" + ); }else//⽂件,直接下载{DownLoadFile(ftpDir + "/" + , saveDir + "\\" + ); }}}#endregion}#region⽂件信息结构public struct FileStruct{public string Flags;public string Owner;public string Group;public bool IsDirectory;public DateTime CreateTime;public string Name;}public enum FileListStyle{UnixStyle,WindowsStyle,Unknown}#endregion。
FTP文件传送

8 2013-7-16
6.2 上传文件工具――CuteFTP CuteFTP采用交互式界面与FTP服务器建 立连接,连接成功之后允许用户进行上传 或下载文件,是目前市场上比较优秀的一 种FTP客户端软件,使用CuteFTP不再需要 记忆一些FTP的命令,是一种非计算机专 业人员连接FTP服务器的一种最佳途径。 CuteFTP具有很多强大的功能,例如支 持断点续传、上传文件和下载文件等功能。 另外还有站点切换方便、使用简便快捷、 操作界面友好等优点
13 2013-7-16
6.2.4 CuteFTP的文件上传和下载
1.文件上传 在利用CuteFTP软件进行文件上传之前,必须要先和 FTP服务器建立连接。当与FTP服务器建立连接之后,用 鼠标把窗口左下部准备上传的文件或文件夹托拽到右下 部的相应的目录上,此时会弹出一个“确认”对话框, 单击“是”按钮,CuteFTP便开始上传。 2.文件的下载 与文件上传一样,在利用CuteFTP软件进行文件下载之 前,必须要先和FTP服务器建立连接,当与FTP服务器建 立连接之后,用鼠标把窗口右下部准备下载的文件或文 件夹托拽到左下部的相应的目录上,此时同样会弹出一 个“确认”对话框,单击“是”按钮,CuteFTP便开始 下载。
17 2013-7-16
6.4 在IIS上建立FTP服务器
6.4.1 FTP服务器的安装 在Windows 2000 Server中的IIS上,建 立FTP服务器,安装的方法如下: (1)Windows 2000 Server启动之后,依 次选择“开始→设置→控制面板→添加/ 删除程序”,打开“添加/删除程序”窗 口。 (2)然后单击“添加/删除 Windows 组 件”,打开“Windows 组件向导”窗口
9 2013-7-16
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
8.1.1 文件传输的基本概念
文件传输服务是由FTP应用程序提供的,而FTP应用程序遵循的是TCP/IP中 的文件传输协议(File Transfer Protocol,即FTP),它允许用户将文件从一台
计算机传输到另一台计算机,并且能保证传输的可靠性。
FTP协议采用典型的C/S模式,在传输层选择TCP协议。图8.1描述了文件 传输的工作过程。
表8-2
方法
FtpWebRequest类的常用方法
含义
Abort BeginGetRequestStream
BeginGetResponse
已重写。终止异步FTP操作 已重写。开始以异步方式打开请求的内容流以便写入
已重写。开始以异步方式向 FTP服务器发送请求并从 FTP 服务器接收响 应
Create CreateDefault EndGetRequestStream EndGetResponse GetRequestStream GetResponse
… FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftpUriString); … FtpWebResponse response = (FtpWebResponse)request.GetResponse( ); …
表8-3和表8-4分别列出了FtpWebResponse类的常用属性和方法。
匿名FTP(anonymous FTP)服务的实质是:提供服务的机构在它的FTP服
务器上建立一个公开账户(通常为Anonymous),并赋予该账户访问公共目录 的权限,以便提供免费的服务。如果用户要访问提供匿名服务的FTP服务器,不
需要输入用户名和密码。如果需要输入它们的话,也是用系统默认的公开账户,
表8-1和表8-2分别列出了FtpWebRequest类的常用属性和方法。
属性 Credentials EnableSsl KeepAlive Method RenameTo RequestUri Timeout UseBinary UsePassive 含义 已重写。获取或设置用于与FTP服务器通信的凭据 获取或设置Boolean,它指定是否使用SSL连接 获取或设置一个Boolean值,该值指定在请求完成之后是否保持到FTP服务器的 控制连接 已重写。获取或设置要发送到FTP服务器的命令 获取或设置重命名文件的新名称 已重写。获取此实例所请求的URI 已重写。获取或设置等待请求的毫秒数 获取或设置一个Boolean值,该值指定文件传输的数据类型。若要传输文本数 据,请将UseBinary属性由默认值true更改为false 获取或设置客户端应用程序的数据传输过程的行为
表8-5列出了NetworkCredential类的常用属性。
属性
UserName Password
含义
获取或设置与凭据关联的用户名 获取或设置与凭据关联的用户名的密码
Domain
获取或设置验证凭据的域名或计算机名
8.3.1FTP工具常用功能及工作流程 在使用FTP工具时,首先要登录服务器,验证登录用户是否合法。如果登录 成功,便可以上传本地文件或文件夹,同时也可以管理FTP服务器端文件,包括 下载、删除文件以及变更、访问、重命名目录、创建新目录等。通常FTP工具的 工作流程如图8.2所示。
ResponseUri
StatusCode StatusDescription WelcomeMessage
已重写。获取对请求发送响应的URI
获取从FTP服务器上发送的最新状态代码 获取描述从FTP服务器发送的状态代码的文本 获取身份验证完成时FTP服务器发送的消息
方法 Close GetResponseStream 已重写。释放响应所持有的资源
4. 变更访问目录
FTP客户端支持用户变更当前目录,与操作【我的电脑】资源管理器类似, 双击目录名进入相应的文件夹,双击“↑返回上层目录”退回到浏览过的上一
级文件夹,如图8.5。这样用户就可以地访问FTP上的所有信息资源了。
变更目录的模块代码。
5. 上传文件 向服务器上传文件的代码。 GetUriString( )方法的实现过程如下: private string GetUriString(string fileName) { string uri = string.Empty; if (currentDir.EndsWith("/")) { uri = ftpUriString + currentDir + fileName; } else { uri = ftpUriString + currentDir + "/" + fileName; } return uri; }
已重载。初始化新的WebRequest(从WebRequest继承) 为指定的URI方案初始化新的WebRequest实例(从WebRequest继承) 已重写。结束由BeginGetRequestStream启动的挂起的异步操作 已重写。结束由BeginGetResponse启动的挂起的异步操作 已重写。检索用于向FTP服务器上载数据的流 已重写。返回FTP服务器响应
含义
已重写。检索包含从FTP服务器上发送的响应数据的流
在命名空间下,有一个NetworkCredential类。该类用于提供客 户端身份验证机制的凭据。NetworkCredential类是为基于密码的身份验证方案 (如基本、简要、NTLM和Kerberos)提供凭据的基类,不支持基于公钥的身份 验证方法,如安全套接字层(SSL)客户端身份验证。当需要验证访问权限时, 我们需要使用这个类提供FTP服务器需要的用户名和密码,用法为: NetworkCredential myCredentials = new NetworkCredential(“FTP用户名”, " 密码");
开始 用户登录 否 是否登录 是 上传 下载 FTP工具 (客户端) 删除服务 器端文件 显示服务器 端目录 辅助功能 FTP服务器
根据图8.2的流程,设计本章FTP文件上传下载软件的界面如图8.3所示。
软件工程名为“SelftpUpDownloader”,程序界面上各控件的属性描述见表 8-6。
发送命令是使用FtpWebRequest对象。以下代码新建FtpWebRequest对象, 并设置常用属性:
String ftpUriString = ”ftp://”+ftpServerIP+"/”; NetworkCredential networkCredential = new NetworkCredential(UserName, Password); //根据服务器信息创建FtpWebRequest类的对象 FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(ftpUriString); //提供身份验证信息 request.Credentials = networkCredential; //设置请求完成之后是否保持到FTP服务器的控制连接,默认值为True request.KeepAlive = true; //设置传输的数据类型 eBinary = true; //设置所要执行的FTP命令。假设此处为显示指定路径下的文件列表 request.Method=WebRequestMethods.Ftp.ListDirectoryDetails;
2. 程序与FTP服务器的交互 创建FtpWebRequest对象:
private FtpWebRequest CreateFtpWebRequest(string uri, string requestMethod) { FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(uri); request.Credentials = networkCredential; request.KeepAlive = true; eBinary = true; request.Method = requestMethod; return request; }
Name frmMain lstbxFtpResrcs rTbxFtpResView tbxSrvIp tbxUsr chkbxAnonymous tbxPwd btnLogin btnLogout tbxLogin btnUpload btnDownload btnDelete tbxOpt lstbxFtpStats btnExit btnAboutbox 控件类型 Form ListBox RichTextBox TextBox TextBox CheckBox TextBox Button Button TextBox Button Button Button TextBox ListBox Button Button 功能描述 程序主窗体 资源一览区 资源浏览提示 FTP服务器IP地址编辑栏 用户名填写栏 【匿名】复选框 密码输入框 【登录】按钮 【注销】按钮 登录状态提示 【上传…】按钮 【下载…】按钮 【删除】按钮 操作结果提示 连接状态显示区 【退出】按钮 【关于】按钮
8.1 FTP概述
8.2 FTP客户端开发相关类 8.3 FTP文件上传下载器的制作 8.4 FTP上传下载软件测试
• 本章教学目的、要求
理解文件传输的基本概念以及FTP服务的工 作过程。
掌握FTP客户端编程涉及的相关类。 熟悉FTP上传下载器的制作。
• 本章教学重点及难点
FTP客户端编程涉及的相关类。 FTP上传下载器的制作。
比如“anonymous”作为用户名,密码为空;有些FTP服务器可能要求用户用自 己的电子邮件地址作为密码。
8.2.1 FtpWebRequest类 FtpWebRequest类用于实现FTP客户端。若要获得FtpWebRequest的实例, 需使用Create方法,该方法有以下两种重载形式。 1. FtpWebRequest.Create(String) 例如: FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create("ftp://myFTPServer/myFile"); 2. FtpWebRequest.Create(Uri) 例如: Uri siteUri = new Uri("ftp://myFTPServer/myFile"); FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(siteUri);