1.最近项目开发涉及到ftp操作。发现FtpWebRequest类有些操作很麻烦,
例如创建目录只能创建一级目录,多级就失败。删除目录只能删除最后一级的空目录。同样下载也是。
故写下帮助类方便使用。
2.调用方法展示,
1
2
3
4
|
var ftp = new FtpHelper( "111.111.111.111" , "xxxxxxx" , "xxxxxx" ); //初始化ftp,创建ftp对象 ftp.uploadFile( "F:\\wms.zip" , "aaa//bbb" );//参数1本地文件,参数2:ftp的目录 ftp.delDirAll( "aaa" ); //参数 要删除的目录的 路径 ftp.downloadAllFile( "aaa" , "F:\\myfile" ); //参数1:要下载的目录,参数2,保存到本地的目录 |
3.FtpHelper 代码。后续再补充说明
1.异常方法委托,通过Lamda委托统一处理异常,方便改写。加了个委托方便控制异常输出
2.递归查找所有目录存入list,然后根据 level排序,从最末级开始遍历删除
3.ftp的目录列表比较怪,暂时用截取字符串的获取 目录或文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
|
/// <summary> /// ftp帮助类 /// </summary> public class FtpHelper { private string ftpHostIP { get ; set ; } private string username { get ; set ; } private string password { get ; set ; } private string ftpURI { get { return $ @"ftp://{ftpHostIP}/" ; } } /// <summary> /// 初始化ftp参数 /// </summary> /// <param name="ftpHostIP">ftp主机IP</param> /// <param name="username">ftp账户</param> /// <param name="password">ftp密码</param> public FtpHelper( string ftpHostIP, string username, string password) { this .ftpHostIP = ftpHostIP; this .username = username; this .password = password; } /// <summary> /// 异常方法委托,通过Lamda委托统一处理异常,方便改写 /// </summary> /// <param name="method">当前执行的方法</param> /// <param name="action"></param> /// <returns></returns> private bool MethodInvoke( string method, Action action) { if (action != null ) { try { action(); //Logger.Write2File($@"FtpHelper.{method}:执行成功"); FluentConsole.Red.Line($ @"FtpHelper.{method}:执行成功" ); return true ; } catch (Exception ex) { FluentConsole.Red.Line($ @"FtpHelper.{method}:执行失败" , ex.ToString()); // Logger.Write2File(action.GetType().Name, ex.ToString()); return false ; } } else { return false ; } } /// <summary> /// 异常方法委托,通过Lamda委托统一处理异常,方便改写 /// </summary> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="method"></param> /// <param name="func"></param> /// <returns></returns> private T MethodInvoke<T>( string method, Func<T> func) { if (func != null ) { try { FluentConsole.Red.Line($ @"FtpHelper.{method}:执行成功" ); return func(); //Logger.Write2File($@"FtpHelper.{method}:执行成功"); } catch (Exception ex) { FluentConsole.Red.Line($ @"FtpHelper.{method}:执行失败:{ex}" ); // Logger.Write2File($@"FtpHelper.{method}:执行失败", ex.ToString()); return default (T); } } else { return default (T); } } private FtpWebRequest GetRequest( string URI) { //根据服务器信息FtpWebRequest创建类的对象 FtpWebRequest result = (FtpWebRequest)WebRequest.Create(URI); result.Credentials = new NetworkCredential(username, password); result.KeepAlive = false ; result.UsePassive = false ; result.UseBinary = true ; return result; } /// <summary> 上传文件</summary> /// <param name="filePath">需要上传的文件</param> /// <param name="targetDir">目标路径</param> public bool uploadFile( string filePath, string dirName = "" ) { FileInfo fileInfo = new FileInfo(filePath); if (dirName != "" ) makeDir(dirName); string uri = Path.Combine(ftpURI, dirName, fileInfo.Name); return MethodInvoke($ @"uploadFile({filePath},{dirName})" , () => { FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.UploadFile; ftp.ContentLength = fileInfo.Length; int buffLength = 2048; byte [] buff = new byte [buffLength]; int contentLen; using (FileStream fs = fileInfo.OpenRead()) { using (Stream strm = ftp.GetRequestStream()) { contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } strm.Close(); } fs.Close(); } }); } /// <summary> /// 检查目录是否存在 /// </summary> /// <param name="dirName"></param> /// <param name="currentDir"></param> /// <returns></returns> public bool checkDir( string dirName, string currentDir = "" ) { string uri = Path.Combine(ftpURI, currentDir); return MethodInvoke($ @"checkDir({dirName}{currentDir})" , () => { FtpWebRequest ftp = GetRequest(uri); ftp.UseBinary = true ; ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; Stream stream = ftp.GetResponse().GetResponseStream(); using (StreamReader sr = new StreamReader(stream)) { string line = sr.ReadLine(); while (! string .IsNullOrEmpty(line)) { string dir = string .Empty; if (line.IndexOf( "<DIR>" ) > -1) { if (line.Substring(line.IndexOf( "<DIR>" ) + 5).Trim() == dirName) return true ; } line = sr.ReadLine(); } sr.Close(); } stream.Close(); return false ; }); } /// <summary> /// 获取当前目录下的目录及文件 /// </summary> /// param name="ftpfileList"></param> /// <param name="dirName"></param> /// <returns></returns> public List<Ftpfile> getFtpFile( string dirName) { var ftpfileList = new List<Ftpfile>(); string uri = Path.Combine(ftpURI, dirName); return MethodInvoke($ @"getFile({dirName})" , () => { var a = new List<List< string >>(); FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; Stream stream = ftp.GetResponse().GetResponseStream(); using (StreamReader sr = new StreamReader(stream)) { string line = sr.ReadLine(); while (! string .IsNullOrEmpty(line)) { ftpfileList.Add( new Ftpfile { isDir = line.IndexOf( "<DIR>" ) > -1, name = line.Substring(39).Trim(),path= Path.Combine(dirName, line.Substring(39).Trim()) }); line = sr.ReadLine(); } sr.Close(); } return ftpfileList; }); } /// <summary> /// 获取目录下的所有目录及文件包括其子目录和子文件 /// </summary> /// param name="ftpfileList"></param> /// <param name="dirName"></param> /// <returns></returns> public List<Ftpfile> getAllFtpFile(List<Ftpfile> ftpfileList, string dirName, int level = 0) { var flist = new List<Ftpfile>(); string uri = Path.Combine(ftpURI, dirName); return MethodInvoke($ @"getFile({dirName})" , () => { var a = new List<List< string >>(); FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; Stream stream = ftp.GetResponse().GetResponseStream(); using (StreamReader sr = new StreamReader(stream)) { string line = sr.ReadLine(); while (! string .IsNullOrEmpty(line)) { flist.Add( new Ftpfile { isDir = line.IndexOf( "<DIR>" ) > -1, name = line.Substring(39).Trim(), level = level, path= Path.Combine(dirName ,line.Substring(39).Trim()) }); ftpfileList.Add( new Ftpfile { isDir = line.IndexOf( "<DIR>" ) > -1, name = line.Substring(39).Trim(), level = level, path = Path.Combine(dirName, line.Substring(39).Trim()) }); line = sr.ReadLine(); } sr.Close(); } var nflist = flist.Where(x => x.isDir).ToList(); if (nflist.Count == 0) return ftpfileList; else return getAllFtpFile(ftpfileList, Path.Combine(dirName, nflist.First().name), level + 1); }); } /// </summary> /// 在ftp服务器上创建指定目录,父目录不存在则创建 /// </summary> /// <param name="dirName">创建的目录名称</param> public bool makeDir( string dirName) { var dirs = dirName.Split( '\\' ).ToList(); //针对多级目录分割 string currentDir = string .Empty; return MethodInvoke($ @"makeDir({dirName})" , () => { foreach (var dir in dirs) { if (!checkDir(dir, currentDir)) //检查目录不存在则创建 { currentDir = Path.Combine(currentDir, dir); string uri = Path.Combine(ftpURI, currentDir); FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.MakeDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); } else { currentDir = Path.Combine(currentDir, dir); } } }); } /// <summary> /// 删除单个文件 /// </summary> /// <param name="filePath"></param> public bool delFile( string filePath) { string uri = Path.Combine(ftpURI, filePath); return MethodInvoke($ @"deleteFile({filePath})" , () => { FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.DeleteFile; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); }); } /// <summary> /// 删除最末及空目录 /// </summary> /// <param name="dirName"></param> private bool delDir( string dirName) { string uri = Path.Combine(ftpURI, dirName); return MethodInvoke($ @"delDir({dirName})" , () => { FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.RemoveDirectory; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); }); } /// <summary> 删除目录或者其目录下所有的文件 </summary> /// <param name="dirName">目录名称</param> /// <param name="ifDelSub">是否删除目录下所有的文件</param> public void delDirAll( string dirName) { var dlist = getAllFtpFile( new List<Ftpfile>(),dirName); dlist.OrderByDescending(x => x.level); //降序排列,先删除末及文件或空目录 string uri = Path.Combine(ftpURI, dirName); MethodInvoke($ @"delDirAll({dirName})" , () => { foreach (var item in dlist) { if (item.isDir) //判断是目录调用目录的删除方法 delDir(item.path); else delFile(item.path); } }); } /// <summary>文件重命名 </summary> /// <param name="currentFilename">当前名称</param> /// <param name="newFilename">重命名名称</param> /// <param name="currentFilename">所在的目录</param> public bool Rename( string currentFilename, string newFilename, string dirName = "" ) { string uri = Path.Combine(ftpURI, dirName, currentFilename); return MethodInvoke($ @"Rename({currentFilename},{newFilename},{dirName})" , () => { FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.Rename; ftp.RenameTo = newFilename; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); response.Close(); }); } /// <summary> /// 下载单个文件 /// </summary> /// <param name="ftpFilePath">从ftp要下载的文件路径</param> /// <param name="localDir">下载至本地路径</param> /// <param name="filename">文件名</param> public bool downloadFile( string ftpFilePath, string saveDir, string filename) { string tmpname = Guid.NewGuid().ToString(); string uri = Path.Combine(ftpURI, ftpFilePath); return MethodInvoke($ @"downloadFile({ftpFilePath},{saveDir},{filename})" , () => { if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir); FtpWebRequest ftp = GetRequest(uri); ftp.Method = WebRequestMethods.Ftp.DownloadFile; using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (FileStream fs = new FileStream(Path.Combine(saveDir, filename), FileMode.CreateNew)) { byte [] buffer = new byte [2048]; int read = 0; do { read = responseStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, read); } while (!(read == 0)); responseStream.Close(); fs.Flush(); fs.Close(); } responseStream.Close(); } response.Close(); } }); } /// <summary> /// 从FTP下载整个文件夹 /// </summary> /// <param name="dirName">FTP文件夹路径</param> /// <param name="saveDir">保存的本地文件夹路径</param> public void downloadAllFile( string dirName, string saveDir) { MethodInvoke($ @"downloadAllFile({dirName},{saveDir})" , () => { List<Ftpfile> files = getFtpFile(dirName); if (!Directory.Exists(saveDir)) { Directory.CreateDirectory(saveDir); } foreach (var f in files) { if (f.isDir) //文件夹,递归查询 { downloadAllFile(Path.Combine(dirName + f.name), Path.Combine(saveDir + f.name)); } else //文件,直接下载 { downloadFile(Path.Combine(dirName + f.name), saveDir, f.name); } } }); } } public class Ftpfile { public int level { get ; set ; } = 0; public bool isDir { get ; set ; } public string name { get ; set ; } public string path { get ; set ; } = "" ; } |
以上所述是小编给大家介绍的C#开发教程之ftp操作方法整理,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:http://www.cnblogs.com/castyuan/p/5699296.html