c# ftp创建文件(非上传文件)
一.奇葩的故事:
今天项目中遇到这么个奇葩的问题,ftp文件传输完成后要在ftp目录下另一个文件夹下创建对应的空文件,听说是为了文件的完整性,既然这么说,那么就必须这么干,员工服从领导是员工的天职,一来二去,思路有了。两个方案:1.通过ftp创建文件;2.本地创建然后在传输过去。开始觉得ftp创建文件不太好整,毕竟要在远程电脑上创建文件,应该是不被允许的把。所以只能使用另一种方案了,在本地创建文件然后在通过ftp传过去不就行了么,说干就干。主要是项目更改不大,就这么干了。(白干了)然而,遇到奇葩的问题了,传过去后还要修改文件名,还没来的及修改被迁移程序迁走了,还没来的及修改就被迁移了,所以文件名不符合要求了,这都是小事,主要是后面的程序不能执行,传输程序报错,同步程序报错,真所谓的牵一发而动全身。所以,上面说的白干了就是这么个意思。既然遇到问题,就得解决呗,说着只能回到之前的思路上了。那么就只能通过第一种方案了,通过ftp创建文件。网上找了个ftpHelper但是看了确实没有创建文件的函数,但细细看来,和上传文件挺类似的,那么就有了下面的故事。
二.FTPHelper类库:
1 using System;
2 using System.Collections.Generic;
3 using System.IO;
4 using System.Linq;
5 using System.Net;
6 using System.Text;
7 using System.Text.RegularExpressions;
8
9 namespace FTP_Demo
10 {
11 /// <summary>
12 /// FTP帮助类
13 /// </summary>
14 public class FTPHelper
15 {
16 #region 字段
17 string ftpURI;
18 string ftpUserID;
19 string ftpServerIP;
20 string ftpPassword;
21 string ftpRemotePath;
22 #endregion
23
24 /// <summary>
25 /// 连接FTP服务器
26 /// </summary>
27 /// <param name="FtpServerIP">FTP连接地址</param>
28 /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
29 /// <param name="FtpUserID">用户名</param>
30 /// <param name="FtpPassword">密码</param>
31 public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
32 {
33 ftpServerIP = FtpServerIP;
34 ftpRemotePath = FtpRemotePath;
35 ftpUserID = FtpUserID;
36 ftpPassword = FtpPassword;
37 ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
38 }
39
40 /// <summary>
41 /// 上传
42 /// </summary>
43 public void Upload(string filename)
44 {
45 FileInfo fileInf = new FileInfo(filename);
46 FtpWebRequest reqFTP;
47 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileInf.Name));
48 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
49 reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
50 reqFTP.KeepAlive = false;
51 reqFTP.UseBinary = true;
52 reqFTP.ContentLength = fileInf.Length;
53 int buffLength = 2048;
54 byte[] buff = new byte[buffLength];
55 int contentLen;
56 FileStream fs = fileInf.OpenRead();
57 try
58 {
59 Stream strm = reqFTP.GetRequestStream();
60 contentLen = fs.Read(buff, 0, buffLength);
61 while (contentLen != 0)
62 {
63 strm.Write(buff, 0, contentLen);
64 contentLen = fs.Read(buff, 0, buffLength);
65 }
66 strm.Close();
67 fs.Close();
68 }
69 catch (Exception ex)
70 {
71 throw new Exception(ex.Message);
72 }
73 }
74
75 /// <summary>
76 /// 下载
77 /// </summary>
78 public void Download(string filePath, string fileName)
79 {
80 try
81 {
82 FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
83 FtpWebRequest reqFTP;
84 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
85 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
86 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
87 reqFTP.UseBinary = true;
88 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
89 Stream ftpStream = response.GetResponseStream();
90 long cl = response.ContentLength;
91 int bufferSize = 2048;
92 int readCount;
93 byte[] buffer = new byte[bufferSize];
94 readCount = ftpStream.Read(buffer, 0, bufferSize);
95 while (readCount > 0)
96 {
97 outputStream.Write(buffer, 0, readCount);
98 readCount = ftpStream.Read(buffer, 0, bufferSize);
99 }
100 ftpStream.Close();
101 outputStream.Close();
102 response.Close();
103 }
104 catch (Exception ex)
105 {
106 throw new Exception(ex.Message);
107 }
108 }
109
110 /// <summary>
111 /// 删除文件
112 /// </summary>
113 public void Delete(string fileName)
114 {
115 try
116 {
117 FtpWebRequest reqFTP;
118 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
119 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
120 reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
121 reqFTP.KeepAlive = false;
122 string result = String.Empty;
123 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
124 long size = response.ContentLength;
125 Stream datastream = response.GetResponseStream();
126 StreamReader sr = new StreamReader(datastream);
127 result = sr.ReadToEnd();
128 sr.Close();
129 datastream.Close();
130 response.Close();
131 }
132 catch (Exception ex)
133 {
134 throw new Exception(ex.Message);
135 }
136 }
137
138 /// <summary>
139 /// 获取当前目录下明细(包含文件和文件夹)
140 /// </summary>
141 public string[] GetFilesDetailList()
142 {
143 try
144 {
145 StringBuilder result = new StringBuilder();
146 FtpWebRequest ftp;
147 ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
148 ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
149 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
150 WebResponse response = ftp.GetResponse();
151 StreamReader reader = new StreamReader(response.GetResponseStream());
152 string line = reader.ReadLine();
153 line = reader.ReadLine();
154 line = reader.ReadLine();
155 while (line != null)
156 {
157 result.Append(line);
158 result.Append("\n");
159 line = reader.ReadLine();
160 }
161 result.Remove(result.ToString().LastIndexOf("\n"), 1);
162 reader.Close();
163 response.Close();
164 return result.ToString().Split('\n');
165 }
166 catch (Exception ex)
167 {
168 throw new Exception(ex.Message);
169 }
170 }
171
172 /// <summary>
173 /// 获取FTP文件列表(包括文件夹)
174 /// </summary>
175 private string[] GetAllList(string url)
176 {
177 List<string> list = new List<string>();
178 FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(url));
179 req.Credentials = new NetworkCredential(ftpPassword, ftpPassword);
180 req.Method = WebRequestMethods.Ftp.ListDirectory;
181 req.UseBinary = true;
182 req.UsePassive = true;
183 try
184 {
185 using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
186 {
187 using (StreamReader sr = new StreamReader(res.GetResponseStream()))
188 {
189 string s;
190 while ((s = sr.ReadLine()) != null)
191 {
192 list.Add(s);
193 }
194 }
195 }
196 }
197 catch (Exception ex)
198 {
199 throw (ex);
200 }
201 return list.ToArray();
202 }
203
204 /// <summary>
205 /// 获取当前目录下文件列表(不包括文件夹)
206 /// </summary>
207 public string[] GetFileList(string url)
208 {
209 StringBuilder result = new StringBuilder();
210 FtpWebRequest reqFTP;
211 try
212 {
213 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
214 reqFTP.UseBinary = true;
215 reqFTP.Credentials = new NetworkCredential(ftpPassword, ftpPassword);
216 reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
217 WebResponse response = reqFTP.GetResponse();
218 StreamReader reader = new StreamReader(response.GetResponseStream());
219 string line = reader.ReadLine();
220 while (line != null)
221 {
222
223 if (line.IndexOf("<DIR>") == -1)
224 {
225 result.Append(Regex.Match(line, @"[\S]+ [\S]+", RegexOptions.IgnoreCase).Value.Split(' ')[1]);
226 result.Append("\n");
227 }
228 line = reader.ReadLine();
229 }
230 result.Remove(result.ToString().LastIndexOf('\n'), 1);
231 reader.Close();
232 response.Close();
233 }
234 catch (Exception ex)
235 {
236 throw (ex);
237 }
238 return result.ToString().Split('\n');
239 }
240
241 /// <summary>
242 /// 判断当前目录下指定的文件是否存在
243 /// </summary>
244 /// <param name="RemoteFileName">远程文件名</param>
245 public bool FileExist(string RemoteFileName)
246 {
247 string[] fileList = GetFileList("*.*");
248 foreach (string str in fileList)
249 {
250 if (str.Trim() == RemoteFileName.Trim())
251 {
252 return true;
253 }
254 }
255 return false;
256 }
257
258 /// <summary>
259 /// 创建文件夹
260 /// </summary>
261 public void MakeDir(string dirName)
262 {
263 FtpWebRequest reqFTP;
264 try
265 {
266 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
267 reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
268 reqFTP.UseBinary = true;
269 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
270 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
271 Stream ftpStream = response.GetResponseStream();
272 ftpStream.Close();
273 response.Close();
274 }
275 catch (Exception ex)
276 { }
277 }
278
279 /// <summary>
280 /// 获取指定文件大小
281 /// </summary>
282 public long GetFileSize(string filename)
283 {
284 FtpWebRequest reqFTP;
285 long fileSize = 0;
286 try
287 {
288 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
289 reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
290 reqFTP.UseBinary = true;
291 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
292 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
293 Stream ftpStream = response.GetResponseStream();
294 fileSize = response.ContentLength;
295 ftpStream.Close();
296 response.Close();
297 }
298 catch (Exception ex)
299 { }
300 return fileSize;
301 }
302
303 /// <summary>
304 /// 更改文件名
305 /// </summary>
306 public void ReName(string currentFilename, string newFilename)
307 {
308 FtpWebRequest reqFTP;
309 try
310 {
311 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
312 reqFTP.Method = WebRequestMethods.Ftp.Rename;
313 reqFTP.RenameTo = newFilename;
314 reqFTP.UseBinary = true;
315 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
316 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
317 Stream ftpStream = response.GetResponseStream();
318 ftpStream.Close();
319 response.Close();
320 }
321 catch (Exception ex)
322 { }
323 }
324
325 /// <summary>
326 /// 移动文件
327 /// </summary>
328 public void MovieFile(string currentFilename, string newDirectory)
329 {
330 ReName(currentFilename, newDirectory);
331 }
332
333 /// <summary>
334 /// 切换当前目录
335 /// </summary>
336 /// <param name="IsRoot">true:绝对路径 false:相对路径</param>
337 public void GotoDirectory(string DirectoryName, bool IsRoot)
338 {
339 if (IsRoot)
340 {
341 ftpRemotePath = DirectoryName;
342 }
343 else
344 {
345 ftpRemotePath += DirectoryName + "/";
346 }
347 ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
348 }
349
350 /// <summary>
351 /// 创建文件
352 /// </summary>
353 /// <param name="filename">文件名</param>
354 /// <param name="text">内容</param>
355 public void CreateFile(string filename, string text)
356 {
357 int bufferLength = 1024;
358 byte[] buffer = new byte[bufferLength];
359 FtpWebRequest reqFTP;
360 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
361 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
362 reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
363 reqFTP.KeepAlive = false;
364 reqFTP.UseBinary = true;
365 reqFTP.ContentLength = text.Length;
366 buffer = Encoding.Unicode.GetBytes(text);
367 using (Stream stream = reqFTP.GetRequestStream())
368 {
369 int count = buffer.Length;
370 while (count > 0)
371 {
372 if (buffer.Length < bufferLength)
373 {
374 bufferLength = buffer.Length;
375 }
376 stream.Write(buffer, 0, bufferLength);
377 count = count - bufferLength;
378 }
379 }
380 }
381 }
382 }
三.定义ftp创建文件函数:
1 /// <summary>
2 /// 创建文件
3 /// </summary>
4 /// <param name="filename">文件名</param>
5 /// <param name="text">内容</param>
6 public void CreateFile(string filename, string text)
7 {
8 int bufferLength = 1024;
9 byte[] buffer = new byte[bufferLength];
10 FtpWebRequest reqFTP;
11 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
12 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
13 reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
14 reqFTP.KeepAlive = false;
15 reqFTP.UseBinary = true;
16 reqFTP.ContentLength = text.Length;
17 buffer = Encoding.Unicode.GetBytes(text);
18 using (Stream stream = reqFTP.GetRequestStream())
19 {
20 int count = buffer.Length;
21 while (count > 0)
22 {
23 if (buffer.Length < bufferLength)
24 {
25 bufferLength = buffer.Length;
26 }
27 stream.Write(buffer, 0, bufferLength);
28 count = count - bufferLength;
29 }
30 }
31 }
四.注意:
stream.Write(buffer, 0, bufferLength);
由于内容的长度有可能小于 bufferLength,所以做了如上if处理。(在这里被坑过了,提示一下而已!)