1using System;
2using System.Collections.Generic;
3using System.Net;
4using System.IO;
5using System.Windows.Forms;
6using System.Text;
7
8namespace FTPDownLoad
9{
10 class FtpFileInfo
11 {
12 public string FileName;
13 public DateTime ModifyDateTime;
14 public bool IsDirectory;
15 }
16 class FtpHelper
17 {
18 private string ftpServer;
19 private string userName;
20 private string password;
21 FtpWebRequest ftpRequest = null;
22 private string errMsg;
23 public string ErrMsg
24 {
25 get { return errMsg; }
26 set { errMsg = value; }
27 }
28 public bool IsAnonymous
29 {
30 get
31 {
32 return !(userName != null && userName.Trim() != String.Empty
33 && password != null && password.Trim() != string.Empty);
34 }
35 }
36
37 public FtpHelper(string ftpServer, string userName, string password)
38 {
39 this.ftpServer = ftpServer;
40 this.userName = userName;
41 this.password = password;
42 }
43
44 /**//// <summary>
45 /// 取得服务器端的文件链表
46 /// </summary>
47 /// <param name="serverPath"></param>
48 /// <returns></returns>
49 public List<FtpFileInfo> GetFilesList(string serverPath)
50 {
51 List<FtpFileInfo> fileInfoList = new List<FtpFileInfo>();
52 Uri uri = new Uri("ftp://" + ftpServer + serverPath);
53 StreamReader sr = null;
54 try
55 {
56 ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri);
57 if (ftpRequest == null) throw new Exception("无法打开ftp服务器连接");
58 ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails; //列表
59 if (!IsAnonymous)
60 {
61 ftpRequest.Credentials = new NetworkCredential(userName, password);
62 }
63
64 sr = new StreamReader(ftpRequest.GetResponse().GetResponseStream());
65 while (!sr.EndOfStream)//读取列表
66 {
67 //System.Diagnostics.Debug.WriteLine(sr.ReadLine());
68 char[] splitChar = { ' ' };
69 string[] tmpArray = sr.ReadLine().Split(splitChar, StringSplitOptions.RemoveEmptyEntries);
70 if (tmpArray.Length != 9)
71 {
72 continue;
73 }
74 FtpFileInfo ffi = new FtpFileInfo();
75 ffi.IsDirectory = tmpArray[0].StartsWith("d");
76 if (!ffi.IsDirectory)
77 {
78 ffi.FileName = tmpArray[8];
79 fileInfoList.Add(ffi);
80 }
81 else
82 {
83 continue;
84 }
85 }
86 }
87 catch (Exception ex)
88 {
89 //TODO: 异常处理.
90 throw ex;
91 }
92 finally
93 {
94 if (sr != null) sr.Close();
95 }
96
97 foreach (FtpFileInfo ffi in fileInfoList)
98 {
99 ffi.ModifyDateTime = this.GetFileModifyTime(serverPath, ffi.FileName);
100 }
101 return fileInfoList;
102 }
103 /**//// <summary>
104 /// Download
105 /// </summary>
106 /// <param name="serverPath"></param>
107 /// <param name="serverFileName"></param>
108 /// <param name="localPath"></param>
109 /// <param name="localFileName"></param>
110 /// <returns></returns>
111 public bool Download(string serverPath, string serverFileName, string localPath, string localFileName)
112 {
113 if (!Directory.Exists(localPath))
114 {
115 //TODO: 创建文件夹
116 errMsg = "本地路径不存在: " + localPath;
117 return false;
118 }
119 FileStream outputStream = null;
120 Stream ftpStream = null;
121 try
122 {
123 outputStream = new FileStream(localPath + "\\" + localFileName, FileMode.Create);
124 if (outputStream == null)
125 {
126 errMsg = "无法创建本地文件";
127 return false;
128 }
129 ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServer + serverPath + "/" + serverFileName));
130 if (ftpRequest == null)
131 {
132 errMsg = "无法连接服务器";
133 return false;
134 }
135 ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
136 ftpRequest.UseBinary = true;
137 //用户验证
138 if (!IsAnonymous)
139 {
140 ftpRequest.Credentials = new NetworkCredential(userName, password);
141 }
142 ftpStream = ftpRequest.GetResponse().GetResponseStream();
143 int bufferSize = 2048;
144 int readCount;
145 byte[] buffer = new byte[bufferSize];
146
147 while ((readCount = ftpStream.Read(buffer, 0, bufferSize)) > 0)
148 {
149 outputStream.Write(buffer, 0, readCount);
150 }
151 }
152 catch (Exception ex)
153 {
154 errMsg = ex.ToString();
155 return false;
156 }
157 finally
158 {
159 if (ftpStream != null) ftpStream.Close();
160 if (outputStream != null) outputStream.Close();
161 }
162 FileInfo fi = new FileInfo(localPath + "\\" + localFileName);
163 fi.LastWriteTime = GetFileModifyTime(serverPath, serverFileName);
164 return true;
165 }
166
167 public void DownLoadDirectory(String ServerPath, String LocalPath)
168 {
169 //取服务器端要下载的目录里的文件列表
170 List<FtpFileInfo> serFileList = GetFilesList(ServerPath);
171 foreach (FtpFileInfo ftpFile in serFileList)
172 {
173 if (ftpFile.IsDirectory) continue;
174 DateTime modifyTime = ftpFile.ModifyDateTime;
175 string localFileName = modifyTime.ToString("yyyyMMddHHmmss") + "_" + ftpFile.FileName;
176
177 // 如果本地不存在该文件,则说明该文件是比较新的文件,需要下载.
178 if (!File.Exists(LocalPath + "\\" + localFileName))
179 {
180 if (!Download(ServerPath, ftpFile.FileName, LocalPath, localFileName))
181 {
182 MessageBox.Show("下载文件出错!\r\n错误原因: " + ErrMsg);
183 }
184 }
185 }
186 }
187
188 public DateTime GetFileModifyTime(string serverPath, string fileName)
189 {
190 Uri uri = new Uri("ftp://" + ftpServer + serverPath + "/" + fileName);
191 DateTime dt = DateTime.Now;
192 try
193 {
194 ftpRequest = (FtpWebRequest)WebRequest.Create(uri);
195 if (!IsAnonymous)
196 {
197 ftpRequest.Credentials = new NetworkCredential(userName, password);
198 }
199 ftpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp;
200 ftpRequest.UseBinary = true;
201 ftpRequest.UsePassive = false;
202 dt = ((FtpWebResponse)ftpRequest.GetResponse()).LastModified;
203 }
204 catch (Exception ex)
205 {
206 //TODO: 错误处理
207 throw ex;
208 }
209 return dt;
210 }
211 }
212}
posted on 2008-09-26 17:36
天书 阅读(1050)
评论(0) 编辑 收藏 引用