如何遍历一个ftp目录word生成索引目录文件

10757人阅读
转载地址:
下面只是我从转载地址提取的自己需要的部分,加了一下自己的变量。原版本功能更强大,请看链接
using System.Collections.G
using System.L
using System.T
using System.Text.RegularE
using System.G
using System.IO;
using System.N
namespace DataDownloader.Class
& & class FtpExplorer
& & & & pri
& & & & pri
& & & & public FtpExplorer(string username, string password, string uri)
& & & & & & this.username =
& & & & & & this.password =
& & & & & & this.uri =
& & & & #region ftp下载浏览文件夹信息
& & & & /// &summary&
& & & & /// 得到当前目录下的所有目录和文件
& & & & /// &/summary&
& & & & /// &param name=&srcpath&&浏览的目录&/param&
& & & & /// &returns&&/returns&
& & & & public List&FileStruct& GetFileList(string srcpath)
& & & & & & List&FileStruct& list = new List&FileStruct&();
& & & & & & FtpWebRequest reqF
& & & & & & WebResponse response =
& & & & & & string ftpuri = string.Format(&ftp://{0}/{1}&, uri, srcpath);
& & & & & & try
& & & & & & {
& & & & & & & & reqFtp = (FtpWebRequest)FtpWebRequest.Create(ftpuri);
& & & & & & & & reqFtp.UseBinary =
& & & & & & & & reqFtp.Credentials = new NetworkCredential(username, password);
& & & & & & & & reqFtp.Method = WebRequestMethods.Ftp.ListDirectoryD
& & & & & & & & response = reqFtp.GetResponse();
& & & & & & & & list =ListFilesAndDirectories((FtpWebResponse)response).ToList();
& & & & & & & & response.Close();
& & & & & & }
& & & & & & catch
& & & & & & { & & & & &&
& & & & & & & & if (response != null)
& & & & & & & & {
& & & & & & & & & & response.Close();
& & & & & & & & }
& & & & & & }
& & & & & &
& & & & #endregion
&#region 列出目录文件信息
& & & & /// &summary&
& & & & /// 列出FTP服务器上面当前目录的所有文件和目录
& & & & /// &/summary&
& & & & public FileStruct[] ListFilesAndDirectories(FtpWebResponse Response)
& & & & & & //Response = Open(this.Uri, WebRequestMethods.Ftp.ListDirectoryDetails);
& & & & & & StreamReader stream = new StreamReader(Response.GetResponseStream(), Encoding.Default);
& & & & & & string Datastring = stream.ReadToEnd();
& & & & & & FileStruct[] list = GetList(Datastring);
& & & & & &
& & & & /// &summary&
& & & & /// 列出FTP服务器上面当前目录的所有文件
& & & & /// &/summary&
& & & & //public FileStruct[] ListFiles()
& & & & //{
& & & & // & &FileStruct[] listAll = ListFilesAndDirectories();
& & & & // & &List&FileStruct& listFile = new List&FileStruct&();
& & & & // & &foreach (FileStruct file in listAll)
& & & & // & &{
& & & & // & & & &if (!file.IsDirectory)
& & & & // & & & &{
& & & & // & & & & & &listFile.Add(file);
& & & & // & & & &}
& & & & // & &}
& & & & // & &return listFile.ToArray();
& & & & //}
& & & & /// &summary&
& & & & /// 列出FTP服务器上面当前目录的所有的目录
& & & & /// &/summary&
& & & & //public FileStruct[] ListDirectories()
& & & & //{
& & & & // & &FileStruct[] listAll = ListFilesAndDirectories();
& & & & // & &List&FileStruct& listDirectory = new List&FileStruct&();
& & & & // & &foreach (FileStruct file in listAll)
& & & & // & &{
& & & & // & & & &if (file.IsDirectory)
& & & & // & & & &{
& & & & // & & & & & &listDirectory.Add(file);
& & & & // & & & &}
& & & & // & &}
& & & & // & &return listDirectory.ToArray();
& & & & //}
& & & & /// &summary&
& & & & /// 获得文件和目录列表
& & & & /// &/summary&
& & & & /// &param name=&datastring&&FTP返回的列表字符信息&/param&
& & & & private 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();
& & & & & & & & & & f.Name = &..&;
& & & & & & & & & & switch (_directoryListStyle)
& & & & & & & & & & {
& & & & & & & & & & & & case FileListStyle.UnixStyle:
& & & & & & & & & & & & & & f = ParseFileStructFromUnixStyleRecord(s);
& & & & & & & & & & & & & &
& & & & & & & & & & & & case FileListStyle.WindowsStyle:
& & & & & & & & & & & & & & f = ParseFileStructFromWindowsStyleRecord(s);
& & & & & & & & & & & & & &
& & & & & & & & & & }
& & & & & & & & & & if (!(f.Name == &.& || f.Name == &..&))
& & & & & & & & & & {
& & & & & & & & & & & & myListArray.Add(f);
& & & & & & & & & & }
& & & & & & & & }
& & & & & & }
& & & & & & return myListArray.ToArray();
& & & & /// &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).DateTimeF
& & & & & & myDTFI.ShortTimePattern = &t&;
& & & & & & f.CreateTime = DateTime.Parse(dateStr + & & + timeStr, myDTFI);
& & & & & & if (processstr.Substring(0, 5) == &&DIR&&)
& & & & & & {
& & & & & & & & f.IsDirectory =
& & & & & & & & processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();
& & & & & & }
& & & & & & else
& & & & & & {
& & & & & & & & string[] strs = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); & // true);
& & & & & & & & processstr = strs[1];
& & & & & & & & f.IsDirectory =
& & & & & & }
& & & & & & f.Name =
& & & & & &
& & & & /// &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.UnixS
& & & & & & & & }
& & & & & & & & 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.WindowsS
& & & & & & & & }
& & & & & & }
& & & & & & return FileListStyle.U
& & & & /// &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);
& & & & & & f.Size=_cutSubstringFromStringWithTrim(ref processstr, ' ', 0); &&
& & & & & & string yearOrTime = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2];
& & & & & & int m_index = processstr.IndexOf(yearOrTime);
& & & & & & if (yearOrTime.IndexOf(&:&) &= 0) &//time
& & & & & & {
& & & & & & & & processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());
& & & & & & }
& & & & & & f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, ' ', 8)+& &+yearOrTime);
& & & & & &&
& & & & & & f.Name = & //最后就是名称
& & & & & &
& & & & /// &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 retS
#endregion
& & & & public string Username
& & & & & & get { }
& & & & & & set { username = }&
& & & & public string Password
& & & & & & get { }
& & & & & & set { password = }
& & & & public string Uri
& & & & & & get { }
& & & & & & set { uri = }
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:243141次
积分:2531
积分:2531
排名:第11005名
原创:47篇
转载:42篇
评论:20条
(1)(1)(5)(1)(1)(2)(2)(2)(1)(1)(1)(5)(1)(6)(7)(4)(8)(2)(3)(8)(7)(8)(4)(4)(1)(2)(2)Java遍历FTP服务器上的文件
import java.io.IOE
import java.io.PrintW
import mons.net.PrintCommandL
import mons.net.ftp.FTPC
import mons.net.ftp.FTPF
import mons.net.ftp.FTPR
public class FTPListAllFiles {
public FTPC
public FTPListAllFiles(boolean isPrintCommmand){
ftp = new FTPClient();
if(isPrintCommmand){
ftp.addProtocolCommandListener(new PrintCommandListener(new
PrintWriter(System.out)));
public boolean login(String host,int port,String
username,String password) throws IOException{
this.ftp.connect(host,port);
if(FTPReply.isPositiveCompletion(this.ftp.getReplyCode()))
if(this.ftp.login(username,password))
this.ftp.setControlEncoding("GBK");
if(this.ftp.isConnected()){
this.ftp.disconnect();
//关闭连接
public void disConnection() throws IOException
if(this.ftp.isConnected())
this.ftp.disconnect();&
//通过路径获得路径下所有文件 输出文件名&
public void List(String pathName) throws IOException{
if(pathName.startsWith("/")&&pathName.endsWith("/")){
String directory = pathN
this.ftp.changeWorkingDirectory(directory);
FTPFile[] files = this.ftp.listFiles();
for(int i=0;i&files.i++){
System.out.println("得到文件:"+files[i].getName());
if(files[i].isFile()){
if(files[i].isDirectory()){
List(directory+files[i].getName()+"/");
public static void main(String[] args) throws IOException
FTPListAllFiles f = new FTPListAllFiles(true);
if(f.login("192.168.1.100",21, "zhuchao","zhuchao")){
f.List("/app/"); //地址,端口号,用户名,密码
f.disConnection();&
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
您的访问请求被拒绝 403 Forbidden - ITeye技术社区
您的访问请求被拒绝
亲爱的会员,您的IP地址所在网段被ITeye拒绝服务,这可能是以下两种情况导致:
一、您所在的网段内有网络爬虫大量抓取ITeye网页,为保证其他人流畅的访问ITeye,该网段被ITeye拒绝
二、您通过某个代理服务器访问ITeye网站,该代理服务器被网络爬虫利用,大量抓取ITeye网页
请您点击按钮解除封锁&博客访问: 634265
博文数量: 247
博客积分: 4385
博客等级: 上校
技术积分: 2373
注册时间:
IT168企业级官微
微信号:IT168qiye
系统架构师大会
微信号:SACC2013
分类: Python/Ruby
#!/usr/bin/env pythonimport os, sysfrom ftplib import FTPrelease_dir = '/pub/I9200_Release/release'download_path = './'args = len(sys.argv)if args >= 2:&&&&download_path = sys.argv[1]&&&&class MyFTP(FTP):&&&&def __init__(self):&&&&&&&&&&&&self.ftp = FTP().__init__()&&&&&&&&self.i9200_dir = ''&&&&&&&&self.i9200_file = ''&&&&&&&&self.download_file = ''&&&&&&&&&&&&def loginFtp(self):&&&&&&&&self.ftp = FTP('165.213.149.206')&&&&&&&&self.ftp.login('lin.yuan', 'lin.yuan')&&&&&&&&print "Begin here---------->"&&&&&&&&&&&&def getDirFile(self):&&&&&&&&self.i9200_dir = self.ftp.nlst(release_dir)[len(self.ftp.nlst(release_dir)) - 1]&&&&&&&&for item in self.ftp.nlst(self.i9200_dir):&&&&&&&&&&&&if 'I9200' in item and 'ubi.tar' in item:&&&&&&&&&&&&&&&&self.i9200_file = item.split('/')[-1]&&&&&&&&def checkExist(self, path):&&&&&&&&self.download_file = os.path.join(path, self.i9200_file)&&&&&&&&if os.path.isfile(self.download_file):&&&&&&&&&&&&return True&&&&&&&&else:&&&&&&&&&&&&return False&&&&&&&&&&&&&&&&&&&&def downloadFile(self):&&&&&&&&self.ftp.cwd(self.i9200_dir)&&&&&&&&print "Download %s from %s to %s" % (self.i9200_file, self.i9200_dir, self.download_file)&&&&&&&&&&&&self.ftp.retrbinary('RETR %s' % self.i9200_file, open(self.download_file, 'wb').write)&&&&&&&&def quitFtp(self):&&&&&&&&print "End here------------>"&&&&&&&&self.ftp.quit()&&&&&&&&def main():&&&&ftp = MyFTP()&&&&ftp.loginFtp()&&&&ftp.getDirFile()&&&&if not ftp.checkExist(download_path):&&&&&&&&ftp.downloadFile()&&&&else:&&&&&&&&print "You have got the latest version!"&&&&ftp.quitFtp()&&&&&&&&if __name__ == '__main__':&&&&main()
阅读(3345) | 评论(0) | 转发(0) |
相关热门文章
给主人留下些什么吧!~~
请登录后评论。

我要回帖

更多关于 目录索引生成器 的文章

 

随机推荐