设为首页 收藏本站
查看: 3812|回复: 0

C#操作FTP, FTPHelper和SFTPHelper

[复制链接]

尚未签到

发表于 2015-5-27 10:28:24 | 显示全部楼层 |阅读模式
  1. FTPHelper


DSC0000.gif DSC0001.gif


  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO;
  4 using System.Net;
  5 using System.Text;
  6
  7 public class FTPHelper
  8     {
  9         ///
10         /// 上传文件
11         ///
12         /// 需要上传的文件
13         /// 目标路径
14         /// ftp地址
15         /// ftp用户名
16         /// ftp密码
17         public static void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password)
18         {
19             //1. check target
20             string target;
21             if (targetDir.Trim() == "")
22             {
23                 return;
24             }
25             string filename = fileinfo.Name;
26             if (!string.IsNullOrEmpty(filename))
27                 target = filename;
28             else
29                 target = Guid.NewGuid().ToString();  //使用临时文件名
30
31             string URI = "FTP://" + hostname + "/" + targetDir + "/" + target;
32             ///WebClient webcl = new WebClient();
33             System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
34
35             //设置FTP命令 设置所要执行的FTP命令,
36             //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
37             ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
38             //指定文件传输的数据类型
39             ftp.UseBinary = true;
40             ftp.UsePassive = true;
41
42             //告诉ftp文件大小
43             ftp.ContentLength = fileinfo.Length;
44             //缓冲大小设置为2KB
45             const int BufferSize = 2048;
46             byte[] content = new byte[BufferSize - 1 + 1];
47             int dataRead;
48
49             //打开一个文件流 (System.IO.FileStream) 去读上传的文件
50             using (FileStream fs = fileinfo.OpenRead())
51             {
52                 try
53                 {
54                     //把上传的文件写入流
55                     using (Stream rs = ftp.GetRequestStream())
56                     {
57                         do
58                         {
59                             //每次读文件流的2KB
60                             dataRead = fs.Read(content, 0, BufferSize);
61                             rs.Write(content, 0, dataRead);
62                         } while (!(dataRead < BufferSize));
63                         rs.Close();
64                     }
65
66                 }
67                 catch (Exception ex) { }
68                 finally
69                 {
70                     fs.Close();
71                 }
72
73             }
74
75             ftp = null;
76         }
77
78         ///
79         /// 下载文件
80         ///
81         /// 下载至本地路径
82         /// ftp目标文件路径
83         /// 从ftp要下载的文件名
84         /// ftp地址即IP
85         /// ftp用户名
86         /// ftp密码
87         public static void DownloadFile(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
88         {
89             string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
90             string tmpname = Guid.NewGuid().ToString();
91             string localfile = localDir + @"\" + tmpname;
92
93             System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
94             ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
95             ftp.UseBinary = true;
96             ftp.UsePassive = false;
97
98             using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
99             {
100                 using (Stream responseStream = response.GetResponseStream())
101                 {
102                     //loop to read & write to file
103                     using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
104                     {
105                         try
106                         {
107                             byte[] buffer = new byte[2048];
108                             int read = 0;
109                             do
110                             {
111                                 read = responseStream.Read(buffer, 0, buffer.Length);
112                                 fs.Write(buffer, 0, read);
113                             } while (!(read == 0));
114                             responseStream.Close();
115                             fs.Flush();
116                             fs.Close();
117                         }
118                         catch (Exception)
119                         {
120                             //catch error and delete file only partially downloaded
121                             fs.Close();
122                             //delete target file as it's incomplete
123                             File.Delete(localfile);
124                             throw;
125                         }
126                     }
127
128                     responseStream.Close();
129                 }
130
131                 response.Close();
132             }
133
134
135
136             try
137             {
138                 File.Delete(localDir + @"\" + FtpFile);
139                 File.Move(localfile, localDir + @"\" + FtpFile);
140
141
142                 ftp = null;
143                 ftp = GetRequest(URI, username, password);
144                 ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
145                 ftp.GetResponse();
146
147             }
148             catch (Exception ex)
149             {
150                 File.Delete(localfile);
151                 throw ex;
152             }
153
154             // 记录日志 "从" + URI.ToString() + "下载到" + localDir + @"\" + FtpFile + "成功." );
155             ftp = null;
156         }
157
158
159         ///
160         /// 下载文件
161         ///
162         /// 下载至本地路径
163         /// ftp目标文件路径
164         /// 从ftp要下载的文件名
165         /// ftp地址即IP
166         /// ftp用户名
167         /// ftp密码
168         public static byte[] DownloadFileBytes(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
169         {
170             byte[] bts;
171             string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
172             string tmpname = Guid.NewGuid().ToString();
173             string localfile = localDir + @"\" + tmpname;
174
175             System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
176             ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
177             ftp.UseBinary = true;
178             ftp.UsePassive = true;
179
180             using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
181             {
182                 using (Stream responseStream = response.GetResponseStream())
183                 {
184                     //loop to read & write to file
185                     using (MemoryStream fs = new MemoryStream())
186                     {
187                         try
188                         {
189                             byte[] buffer = new byte[2048];
190                             int read = 0;
191                             do
192                             {
193                                 read = responseStream.Read(buffer, 0, buffer.Length);
194                                 fs.Write(buffer, 0, read);
195                             } while (!(read == 0));
196                             responseStream.Close();
197
198                             //---
199                             byte[] mbt = new byte[fs.Length];
200                             fs.Read(mbt, 0, mbt.Length);
201
202                             bts = mbt;
203                             //---
204                             fs.Flush();
205                             fs.Close();
206                         }
207                         catch (Exception)
208                         {
209                             //catch error and delete file only partially downloaded
210                             fs.Close();
211                             //delete target file as it's incomplete
212                             File.Delete(localfile);
213                             throw;
214                         }
215                     }
216
217                     responseStream.Close();
218                 }
219
220                 response.Close();
221             }
222
223             ftp = null;
224             return bts;
225         }
226
227         ///
228         /// 搜索远程文件
229         ///
230         ///
231         ///
232         ///
233         ///
234         ///
235         ///
236         public static List ListDirectory(string targetDir, string hostname, string username, string password, string SearchPattern)
237         {
238             List result = new List();
239             try
240             {
241                 string URI = "FTP://" + hostname + "/" + targetDir + "/" + SearchPattern;
242
243                 System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
244                 ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
245                 ftp.UsePassive = true;
246                 ftp.UseBinary = true;
247
248
249                 string str = GetStringResponse(ftp);
250                 str = str.Replace("\r\n", "\r").TrimEnd('\r');
251                 str = str.Replace("\n", "\r");
252                 if (str != string.Empty)
253                     result.AddRange(str.Split('\r'));
254
255                 return result;
256             }
257             catch { }
258             return null;
259         }
260
261         private static string GetStringResponse(FtpWebRequest ftp)
262         {
263             //Get the result, streaming to a string
264             string result = "";
265             using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
266             {
267                 long size = response.ContentLength;
268                 using (Stream datastream = response.GetResponseStream())
269                 {
270                     using (StreamReader sr = new StreamReader(datastream, System.Text.Encoding.Default))
271                     {
272                         result = sr.ReadToEnd();
273                         sr.Close();
274                     }
275
276                     datastream.Close();
277                 }
278
279                 response.Close();
280             }
281
282             return result;
283         }
284
285         /// 在ftp服务器上创建目录
286         ///
287         /// 创建的目录名称
288         /// ftp地址
289         /// 用户名
290         /// 密码
291         public void MakeDir(string dirName, string ftpHostIP, string username, string password)
292         {
293             try
294             {
295                 string uri = "ftp://" + ftpHostIP + "/" + dirName;
296                 System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
297                 ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
298
299                 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
300                 response.Close();
301             }
302             catch (Exception ex)
303             {
304                 throw new Exception(ex.Message);
305             }
306         }
307
308         ///
309         /// 删除文件
310         ///
311         /// 创建的目录名称
312         /// ftp地址
313         /// 用户名
314         /// 密码
315         public static void delFile(string dirName, string filename, string ftpHostIP, string username, string password)
316         {
317             try
318             {
319                 string uri = "ftp://" + ftpHostIP + "/";
320                 if (!string.IsNullOrEmpty(dirName)) {
321                     uri += dirName + "/";
322                 }
323                 uri += filename;
324                 System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
325                 ftp.Method = WebRequestMethods.Ftp.DeleteFile;
326                 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
327                 response.Close();
328             }
329             catch (Exception ex)
330             {
331                 throw new Exception(ex.Message);
332             }
333         }
334
335         ///
336         /// 删除目录
337         ///
338         /// 创建的目录名称
339         /// ftp地址
340         /// 用户名
341         /// 密码
342         public void delDir(string dirName, string ftpHostIP, string username, string password)
343         {
344             try
345             {
346                 string uri = "ftp://" + ftpHostIP + "/" + dirName;
347                 System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
348                 ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;
349                 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
350                 response.Close();
351             }
352             catch (Exception ex)
353             {
354                 throw new Exception(ex.Message);
355             }
356         }
357
358         ///
359         /// 文件重命名
360         ///
361         /// 当前目录名称
362         /// 重命名目录名称
363         /// ftp地址
364         /// 用户名
365         /// 密码
366         public void Rename(string currentFilename, string newFilename, string ftpServerIP, string username, string password)
367         {
368             try
369             {
370
371                 FileInfo fileInf = new FileInfo(currentFilename);
372                 string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
373                 System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
374                 ftp.Method = WebRequestMethods.Ftp.Rename;
375
376                 ftp.RenameTo = newFilename;
377                 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
378
379                 response.Close();
380             }
381             catch (Exception ex)
382             {
383                 throw new Exception(ex.Message);
384             }
385         }
386
387         private static FtpWebRequest GetRequest(string URI, string username, string password)
388         {
389             //根据服务器信息FtpWebRequest创建类的对象
390             FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
391             //提供身份验证信息
392             result.Credentials = new System.Net.NetworkCredential(username, password);
393             //设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true
394             result.KeepAlive = false;
395             return result;
396         }
397
398         /*
399         ///
400         /// 向Ftp服务器上传文件并创建和本地相同的目录结构
401         /// 遍历目录和子目录的文件
402         ///
403         ///
404         private void GetFileSystemInfos(FileSystemInfo file)
405         {
406             string getDirecName = file.Name;
407             if (!ftpIsExistsFile(getDirecName, "192.168.0.172", "Anonymous", "") && file.Name.Equals(FileName))
408             {
409                 MakeDir(getDirecName, "192.168.0.172", "Anonymous", "");
410             }
411             if (!file.Exists) return;
412             DirectoryInfo dire = file as DirectoryInfo;
413             if (dire == null) return;
414             FileSystemInfo[] files = dire.GetFileSystemInfos();
415
416             for (int i = 0; i < files.Length; i++)
417             {
418                 FileInfo fi = files as FileInfo;
419                 if (fi != null)
420                 {
421                     DirectoryInfo DirecObj = fi.Directory;
422                     string DireObjName = DirecObj.Name;
423                     if (FileName.Equals(DireObjName))
424                     {
425                         UploadFile(fi, DireObjName, "192.168.0.172", "Anonymous", "");
426                     }
427                     else
428                     {
429                         Match m = Regex.Match(files.FullName, FileName + "+.*" + DireObjName);
430                         //UploadFile(fi, FileName+"/"+DireObjName, "192.168.0.172", "Anonymous", "");
431                         UploadFile(fi, m.ToString(), "192.168.0.172", "Anonymous", "");
432                     }
433                 }
434                 else
435                 {
436                     string[] ArrayStr = files.FullName.Split('\\');
437                     string finame = files.Name;
438                     Match m = Regex.Match(files.FullName, FileName + "+.*" + finame);
439                     //MakeDir(ArrayStr[ArrayStr.Length - 2].ToString() + "/" + finame, "192.168.0.172", "Anonymous", "");
440                     MakeDir(m.ToString(), "192.168.0.172", "Anonymous", "");
441                     GetFileSystemInfos(files);
442                 }
443             }
444         }
445          * */
446
447         ///
448         /// 判断ftp服务器上该目录是否存在
449         ///
450         ///
451         ///
452         ///
453         ///
454         ///
455         private bool ftpIsExistsFile(string dirName, string ftpHostIP, string username, string password)
456         {
457             bool flag = true;
458             try
459             {
460                 string uri = "ftp://" + ftpHostIP + "/" + dirName;
461                 System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
462                 ftp.Method = WebRequestMethods.Ftp.ListDirectory;
463
464                 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
465                 response.Close();
466             }
467             catch (Exception)
468             {
469                 flag = false;
470             }
471             return flag;
472         }
473     }
View Code   
2. SFTPHelper
  SFTPHelper采用第三方的Tamir.SharpSSH.dll
  下载地址: http://www.tamirgal.com/blog/page/SharpSSH.aspx





  1 using System;
  2 using Tamir.SharpSsh.jsch;
  3 using System.Collections;
  4
  5
  6 public class SFTPHelper
  7 {
  8     private Session m_session;
  9     private Channel m_channel;
10     private ChannelSftp m_sftp;
11
12     //host:sftp地址   user:用户名   pwd:密码        
13     public SFTPHelper(string host, string user, string pwd)
14     {
15         string[] arr = host.Split(':');
16         string ip = arr[0];
17         int port = 22;
18         if (arr.Length > 1) port = Int32.Parse(arr[1]);
19
20         JSch jsch = new JSch();
21         m_session = jsch.getSession(user, ip, port);
22         MyUserInfo ui = new MyUserInfo();
23         ui.setPassword(pwd);
24         m_session.setUserInfo(ui);
25
26     }
27
28     //SFTP连接状态        
29     public bool Connected { get { return m_session.isConnected(); } }
30
31     //连接SFTP        
32     public bool Connect()
33     {
34         try
35         {
36             if (!Connected)
37             {
38                 m_session.connect();
39                 m_channel = m_session.openChannel("sftp");
40                 m_channel.connect();
41                 m_sftp = (ChannelSftp)m_channel;
42             }
43             return true;
44         }
45         catch
46         {
47             return false;
48         }
49     }
50
51     //断开SFTP        
52     public void Disconnect()
53     {
54         if (Connected)
55         {
56             m_channel.disconnect();
57             m_session.disconnect();
58         }
59     }
60
61     //SFTP存放文件        
62     public bool Put(string localPath, string remotePath)
63     {
64         try
65         {
66             Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(localPath);
67             Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(remotePath);
68             m_sftp.put(src, dst);
69             return true;
70         }
71         catch
72         {
73             return false;
74         }
75     }
76
77     //SFTP获取文件        
78     public bool Get(string remotePath, string localPath)
79     {
80         try
81         {
82             Tamir.SharpSsh.java.String src = new Tamir.SharpSsh.java.String(remotePath);
83             Tamir.SharpSsh.java.String dst = new Tamir.SharpSsh.java.String(localPath);
84             m_sftp.get(src, dst);
85             return true;
86         }
87         catch
88         {
89             return false;
90         }
91     }
92     //删除SFTP文件
93     public bool Delete(string remoteFile)
94     {
95         try
96         {
97             m_sftp.rm(remoteFile);
98             return true;
99         }
100         catch
101         {
102             return false;
103         }
104     }
105
106     //获取SFTP文件列表        
107     public ArrayList GetFileList(string remotePath, string fileType)
108     {
109         try
110         {
111             Tamir.SharpSsh.java.util.Vector vvv = m_sftp.ls(remotePath);
112             ArrayList objList = new ArrayList();
113             foreach (Tamir.SharpSsh.jsch.ChannelSftp.LsEntry qqq in vvv)
114             {
115                 string sss = qqq.getFilename();
116                 if (sss.Length > (fileType.Length + 1) && fileType == sss.Substring(sss.Length - fileType.Length))
117                 { objList.Add(sss); }
118                 else { continue; }
119             }
120
121             return objList;
122         }
123         catch
124         {
125             return null;
126         }
127     }
128
129
130     //登录验证信息        
131     public class MyUserInfo : UserInfo
132     {
133         String passwd;
134         public String getPassword() { return passwd; }
135         public void setPassword(String passwd) { this.passwd = passwd; }
136
137         public String getPassphrase() { return null; }
138         public bool promptPassphrase(String message) { return true; }
139
140         public bool promptPassword(String message) { return true; }
141         public bool promptYesNo(String message) { return true; }
142         public void showMessage(String message) { }
143     }
144
145
146 }
View Code   

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-71158-1-1.html 上篇帖子: 【下载】Altera开发套件所有版本FTP下载地址 下篇帖子: HTTP/FTP客户端开发库:libwww、libcurl、libfetch 以及更多
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表