ftp⽂件操作类(上传、下载、删除、创建、重命名、获取⽬录中
的所有⽂件)
ftp⽂件操作类
1using System;
2using System.Collections.Generic;
param name3using System.Linq;
4using System.Text;
5using System.Net;
6using System.IO;
7using System.Data;
8using System.ComponentModel;
9using System.Windows.Forms;
10using System.Text.RegularExpressions;
11using System.Globalization;
12using System.Collections;
13
14namespace ESIMRobot
15 {
16#region⽂件信息结构
17public struct FileStruct
18 {
19public string Flags;
20public string Owner;
21public string Group;
22public bool IsDirectory;
23public DateTime CreateTime;
24public string Name;
25 }
26public enum FileListStyle
27 {
28 UnixStyle,
29 WindowsStyle,
30 Unknown
31 }
32#endregion
33
34///<summary>
35/// ftp⽂件上传、下载操作类
36///</summary>
37public class FTPHelper
38 {
39private string ftpServerURL;
40private string ftpUser;
41private string ftpPassWord;
42
43///<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 }
65
66///<summary>
67///匿名访问
68///</summary>
69public FTPHelper(string ftpURL)
70 {
71this.ftpUser = "";
72this.ftpPassWord = "";
73 }
74
75
76//**************************************************** Start_1 *********************************************************//
77///<summary>
78///从FTP下载⽂件到本地服务器,⽀持断点下载
79///</summary>
80///<param name="ftpFilePath">ftp⽂件路径,如"ftp://"</param>
81///<param name="saveFilePath">保存⽂件的路径,如C:\\</param>
82public void BreakPointDownLoadFile(string ftpFilePath, string saveFilePath)
83 {
84 System.IO.FileStream fs = null;
85 System.Net.FtpWebResponse ftpRes = null;
86 System.IO.Stream resStrm = null;
87try
88 {
89//下载⽂件的URI
90 Uri uri = new Uri(ftpFilePath);
91//设定下载⽂件的保存路径
92string downFile = saveFilePath;
93
94//FtpWebRequest的作成
95 System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)
96 System.Net.WebRequest.Create(uri);
97//设定⽤户名和密码
98 ftpReq.Credentials = new System.Net.NetworkCredential(ftpUser, ftpPassWord);
99//MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定
100 ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
101//要求终了后关闭连接
102 ftpReq.KeepAlive = false;
103//使⽤ASCII⽅式传送
104 ftpReq.UseBinary = false;
105//设定PASSIVE⽅式⽆效
106 ftpReq.UsePassive = false;
107
108//判断是否继续下载
109//继续写⼊下载⽂件的FileStream
110if (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 }
117else
118 {
119//⼀般下载
120 fs = new System.IO.FileStream(
121 downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
122 }
123
124//取得FtpWebResponse
125 ftpRes = (System.Net.FtpWebResponse)ftpReq.GetResponse();
126//为了下载⽂件取得Stream
127 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 }
142finally
143 {
144 fs.Close();
145 resStrm.Close();
146 ftpRes.Close();
147 }
148 }
149
150
151#region
152//从FTP上下载整个⽂件夹,包括⽂件夹下的⽂件和⽂件夹函数列表
153
154///<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;
164try
165 {
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();
172
173 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 }
188finally
189 {
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 }
204
205
206///<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;
216try
217 {
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);
230
231 }
232
233///<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 }
251
252
253///<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 }
271
272
273///<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 f.Name = "..";
288switch (_directoryListStyle)
289 {
290case FileListStyle.UnixStyle:
291 f = ParseFileStructFromUnixStyleRecord(s);
292break;
293case FileListStyle.WindowsStyle:
294 f = ParseFileStructFromWindowsStyleRecord(s);
295break;
296 }
297if (!(f.Name == "." || f.Name == ".."))
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) //time
322 {
323 processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());
324 }
325 f.CreateTime = DateTime.Parse(cutSubstringFromStringWithTrim(ref processstr, '', 8));
326 f.Name = processstr; //最后就是名称
327return f;
328 }
329
330///<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 }
350else
351 {
352string[] strs = processstr.Split(new char[] { '' }, 2);// StringSplitOptions.RemoveEmptyEntries); // true); 353 processstr = strs[1];
354 f.IsDirectory = false;
355 }
356 f.Name = processstr;
357return f;
358 }
359
360
361///<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 }
374
375
376///<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 > 10
385 && 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 > 8
390 && 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 }
397
398
399///<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;
410try
411 {
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) //⽂件夹,递归查询
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论