• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#操作FTP,FTPHelper和SFTPHelper

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

1. FTPHelper

  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         /// <summary>
 10         /// 上传文件
 11         /// </summary>
 12         /// <param name="fileinfo">需要上传的文件</param>
 13         /// <param name="targetDir">目标路径</param>
 14         /// <param name="hostname">ftp地址</param>
 15         /// <param name="username">ftp用户名</param>
 16         /// <param name="password">ftp密码</param>
 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         /// <summary>
 79         /// 下载文件
 80         /// </summary>
 81         /// <param name="localDir">下载至本地路径</param>
 82         /// <param name="FtpDir">ftp目标文件路径</param>
 83         /// <param name="FtpFile">从ftp要下载的文件名</param>
 84         /// <param name="hostname">ftp地址即IP</param>
 85         /// <param name="username">ftp用户名</param>
 86         /// <param name="password">ftp密码</param>
 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         /// <summary>
160         /// 下载文件
161         /// </summary>
162         /// <param name="localDir">下载至本地路径</param>
163         /// <param name="FtpDir">ftp目标文件路径</param>
164         /// <param name="FtpFile">从ftp要下载的文件名</param>
165         /// <param name="hostname">ftp地址即IP</param>
166         /// <param name="username">ftp用户名</param>
167         /// <param name="password">ftp密码</param>
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         /// <summary>
228         /// 搜索远程文件
229         /// </summary>
230         /// <param name="targetDir"></param>
231         /// <param name="hostname"></param>
232         /// <param name="username"></param>
233         /// <param name="password"></param>
234         /// <param name="SearchPattern"></param>
235         /// <returns></returns>
236         public static List<string> ListDirectory(string targetDir, string hostname, string username, string password, string SearchPattern)
237         {
238             List<string> result = new List<string>();
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         /// </summary>
287         /// <param name="dirName">创建的目录名称</param>
288         /// <param name="ftpHostIP">ftp地址</param>
289         /// <param name="username">用户名</param>
290         /// <param name="password">密码</param>
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         /// <summary>
309         /// 删除文件
310         /// </summary>
311         /// <param name="dirName">创建的目录名称</param>
312         /// <param name="ftpHostIP">ftp地址</param>
313         /// <param name="username">用户名</param>
314         /// <param name="password">密码</param>
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         /// <summary>
336         /// 删除目录
337         /// </summary>
338         /// <param name="dirName">创建的目录名称</param>
339         /// <param name="ftpHostIP">ftp地址</param>
340         /// <param name="username">用户名</param>
341         /// <param name="password">密码</param>
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                 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++结构体指针发布时间:2022-07-13
下一篇:
C#匿名函数发布时间:2022-07-13
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap