1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.IO;
5 using System.Net;
6 using System.Globalization;
7 using System.IO.Compression;
8 using ICSharpCode.SharpZipLib.Zip;
9 using ICSharpCode.SharpZipLib.GZip;
10 using ICSharpCode.SharpZipLib.Tar;
11
12 namespace ClassProject.FTP
13 {
14 class FtpWeb
15 {
16 string ftpServerIP;
17 string ftpRemotePath;
18 string ftpUserID;
19 string ftpPassword;
20 string ftpURI;
21 /// <summary>
22 /// 连接FTP
23 /// </summary>
24 /// <param name="FtpServerIP">FTP连接地址</param>
25 /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
26 /// <param name="FtpUserID">用户名</param>
27 /// <param name="FtpPassword">密码</param>
28 public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
29 {
30 ftpServerIP = FtpServerIP;
31 ftpRemotePath = FtpRemotePath;
32 ftpUserID = FtpUserID;
33 ftpPassword = FtpPassword;
34 ftpURI = "ftp://" + ftpServerIP + "/";
35 }
36 //测试用例--已成功
37 //static void Main()
38 //{
39 // FtpWeb fw = new FtpWeb(@"xxxxxx/FTPFile", @"C:\Users\Administrator\Desktop\dic\", "user", "password");
40 // string[] a = fw.NEWGetFileList(@"FTPFile");
41 // string path = @"C:\Users\Administrator\Desktop\新建文件夹";
42 // string X = "START:";
43 // for (int i = 0; i < a.Length; i++)
44 // {
45 // fw.Download(path, a[i].ToString(),'Active');
46 // fw.Delete(a[i].ToString());
47 // X += a[i] + "、";
48 // }
49 // Console.WriteLine("x");
50 // Console.ReadLine();
51 //}
52 //上传文件
53 public string UploadFile(string[] filePaths)
54 {
55 StringBuilder sb = new StringBuilder();
56 if (filePaths != null && filePaths.Length > 0)
57 {
58 foreach (var file in filePaths)
59 {
60 sb.Append(Upload(file, "Active"));
61 }
62 }
63 return sb.ToString();
64 }
65 /// <summary>
66 /// 上传文件
67 /// </summary>
68 /// <param name="filename"></param>
69 public string Upload(string filename,string type)
70 {
71 FileInfo fileInf = new FileInfo(filename);
72 if (!fileInf.Exists)
73 {
74 return filename + " 不存在!\n";
75 }
76 string uri = ftpURI + fileInf.Name;
77 FtpWebRequest reqFTP;
78 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
79 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
80 reqFTP.KeepAlive = false;
81 reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
82 reqFTP.UseBinary = true;
83 if (type=="Active")
84 {
85 reqFTP.UsePassive = false; //选择主动
86 }
87 else
88 {
89 reqFTP.UsePassive = true; //选择被动模式
90 }
91
92 //Entering Passive Mode
93 reqFTP.ContentLength = fileInf.Length;
94 int buffLength = 2048;
95 byte[] buff = new byte[buffLength];
96 int contentLen;
97 FileStream fs = fileInf.OpenRead();
98 try
99 {
100 Stream strm = reqFTP.GetRequestStream();
101 contentLen = fs.Read(buff, 0, buffLength);
102 while (contentLen != 0)
103 {
104 strm.Write(buff, 0, contentLen);
105 contentLen = fs.Read(buff, 0, buffLength);
106 }
107 strm.Close();
108 fs.Close();
109 }
110 catch (Exception ex)
111 {
112 return "同步 " + filename + "时连接不上服务器!\n";
113 //Insert_Standard_ErrorLog.Insert("FtpWeb", "Upload Error --> " + ex.Message);
114 }
115 return "";
116 }
117 /// <summary>
118 /// 下载
119 /// </summary>
120 /// <param name="filePath"></param>
121 /// <param name="fileName"></param>
122 public void Download(string filePath, string fileName, string type)
123 {
124 FtpWebRequest reqFTP;
125 try
126 {
127 FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
128 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
129 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
130 reqFTP.UseBinary = true;
131 if (type == "Active")
132 {
133 reqFTP.UsePassive = false; //选择主动
134 }
135 else
136 {
137 reqFTP.UsePassive = true; //选择被动模式
138 }
139 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
140 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
141 Stream ftpStream = response.GetResponseStream();
142 long cl = response.ContentLength;
143 int bufferSize = 2048;
144 int readCount;
145 byte[] buffer = new byte[bufferSize];
146 readCount = ftpStream.Read(buffer, 0, bufferSize);
147 while (readCount > 0)
148 {
149 outputStream.Write(buffer, 0, readCount);
150 readCount = ftpStream.Read(buffer, 0, bufferSize);
151 }
152 ftpStream.Close();
153 outputStream.Close();
154 response.Close();
155 }
156 catch (Exception ex)
157 {
158 // Insert_Standard_ErrorLog.Insert("FtpWeb", "Download Error --> " + ex.Message);
159 }
160 }
161 /// <summary>
162 /// 删除文件
163 /// </summary>
164 /// <param name="fileName"></param>
165 public void Delete(string fileName, string type)
166 {
167 try
168 {
169 string uri = ftpURI + fileName;
170 FtpWebRequest reqFTP;
171 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
172 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
173 reqFTP.KeepAlive = false;
174 if (type == "Active")
175 {
176 reqFTP.UsePassive = false; //选择主动
177 }
178 else
179 {
180 reqFTP.UsePassive = true; //选择被动模式
181 }
182 reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
183 string result = String.Empty;
184 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
185 long size = response.ContentLength;
186 Stream datastream = response.GetResponseStream();
187 StreamReader sr = new StreamReader(datastream);
188 result = sr.ReadToEnd();
189 sr.Close();
190 datastream.Close();
191 response.Close();
192 }
193 catch (Exception ex)
194 {
195 //Insert_Standard_ErrorLog.Insert("FtpWeb", "Delete Error --> " + ex.Message + " 文件名:" + fileName);
196 }
197 }
198
199 /// <summary>
200 /// 删除文件
201 /// </summary>
202 /// <param name="srcPath">文件的路径</param>
203 public void DelectDir(string srcPath)
204 {
205 try
206 {
207 DirectoryInfo dir = new DirectoryInfo(srcPath);
208 FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); //返回目录中所有文件和子目录
209 foreach (FileSystemInfo i in fileinfo)
210 {
211 if (i is DirectoryInfo) //判断是否文件夹
212 {
213 DirectoryInfo subdir = new DirectoryInfo(i.FullName);
214 subdir.Delete(true); //删除子目录和文件
215 }
216 else
217 {
218 File.Delete(i.FullName); //删除指定文件
219 }
220 }
221 }
222 catch (Exception e)
223 {
224 throw;
225 }
226 }
227
228 /// <summary>
229 /// 获取当前目录下明细(包含文件和文件夹)
230 /// </summary>
231 /// <returns></returns>
232 public string[] GetFilesDetailList()
233 {
234 string[] downloadFiles;
235 try
236 {
237 StringBuilder result = new StringBuilder();
238 FtpWebRequest ftp;
239 ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
240 ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
241 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
242 WebResponse response = ftp.GetResponse();
243 StreamReader reader = new StreamReader(response.GetResponseStream());
244 string line = reader.ReadLine();
245 line = reader.ReadLine();
246 line = reader.ReadLine();
247 while (line != null)
248 {
249 result.Append(line);
250 result.Append("\n");
251 line = reader.ReadLine();
252 }
253 result.Remove(result.ToString().LastIndexOf("\n"), 1);
254 reader.Close();
255 response.Close();
256 return result.ToString().Split('\n');
257 }
258 catch (Exception ex)
259 {
260 downloadFiles = null;
261 //Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFilesDetailList Error --> " + ex.Message);
262 return downloadFiles;
263 }
264 }
265 /// <summary>
266 /// 获取当前目录下文件列表(仅文件)
267 /// </summary>
268 /// <returns></returns>
269 public string[] GetFileList(string mask, string type)
270 {
271 string[] downloadFiles;
272 StringBuilder result = new StringBuilder();
273 FtpWebRequest reqFTP;
274 try
275 {
276 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
277 reqFTP.UseBinary = true;
278 if (type == "Active")
279 {
280 reqFTP.UsePassive = false; //选择主动
281 }
282 else
283 {
284 reqFTP.UsePassive = true; //选择被动模式
285 }
286 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
287 reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
288 WebResponse response = reqFTP.GetResponse();
289 StreamReader reader = new StreamReader(response.GetResponseStream());
290 string line = reader.ReadLine();
291 while (line != null)
292 {
293 if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
294 {
295 string mask_ = mask.Substring(0, mask.IndexOf("*"));
296 if (line.Substring(0, mask_.Length) == mask_)
297 {
298 result.Append(line);
299 result.Append("\n");
300 }
301 }
302 else
303 {
304 result.Append(line);
305 result.Append("\n");
306 }
307 line = reader.ReadLine();
308 }
309 result.Remove(result.ToString().LastIndexOf('\n'), 1);
310 reader.Close();
311 response.Close();
312 return result.ToString().Split('\n');
313 }
314 catch (Exception ex)
315 {
316 downloadFiles = null;
317 if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。")
318 {
319 //Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFileList Error --> " + ex.Message.ToString());
320 }
321 return downloadFiles;
322 }
323 }
324 /// <summary>
325 /// 获取当前目录下文件列表(仅文件)
326 /// </summary>
327 /// <returns></returns>
328 public string[] NEWGetFileList(string mask,string type)
329 {
330 string[] downloadFiles;
331 StringBuilder result = new StringBuilder();
332 FtpWebRequest reqFTP;
333 try
334 {
335 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
336 reqFTP.UseBinary = true;
337 if (type == "Active")
338 {
339 reqFTP.UsePassive = false; //选择主动
340 }
341 else
342 {
343 reqFTP.UsePassive = true; //选择被动模式
344 }
345 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
346 reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
347 WebResponse response = reqFTP.GetResponse();
348 StreamReader reader = new StreamReader(response.GetResponseStream());
349 string line = reader.ReadLine();
350 while (line != null)
351 {
352 if (mask.Trim() != string.Empty && mask.Trim() != "*.*")
353 {
354 result.Append(line);
355 result.Append("\n");
356 }
357 line = reader.ReadLine();
358 }
359 result.Remove(result.ToString().LastIndexOf('\n'), 1);
360 reader.Close();
361 response.Close();
362 return result.ToString().Split('\n');
363 }
364 catch (Exception ex)
365 {
366 downloadFiles = null;
367 if (ex.Message.Trim() != "远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。")
368 {
369 //Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFileList Error --> " + ex.Message.ToString());
370 }
371 return downloadFiles;
372 }
373 }
374 /// <summary>
375 /// 获取当前目录下所有的文件夹列表(仅文件夹)
376 /// </summary>
377 /// <returns></returns>
378 public string[] GetDirectoryList()
379 {
380 string[] drectory = GetFilesDetailList();
381 string m = string.Empty;
382 foreach (string str in drectory)
383 {
384 if (str.Trim().Substring(0, 1).ToUpper() == "D")
385 {
386 m += str.Substring(54).Trim() + "\n";
387 }
388 }
389 char[] n = new char[] { '\n' };
390 return m.Split(n);
391 }
392 /// <summary>
393 /// 判断当前目录下指定的子目录是否存在
394 /// </summary>
395 /// <param name="RemoteDirectoryName">指定的目录名</param>
396 public bool DirectoryExist(string RemoteDirectoryName)
397 {
398 string[] dirList = GetDirectoryList();
399 foreach (string str in dirList)
400 {
401 if (str.Trim() == RemoteDirectoryName.Trim())
402 {
403 return true;
404 }
405 }
406 return false;
407 }
408 /// <summary>
409 /// 判断当前目录下指定的文件是否存在
410 /// </summary>
411 /// <param name="RemoteFileName">远程文件名</param>
412 public bool FileExist(string RemoteFileName)
413 {
414 string[] fileList = GetFileList("*.*", "Active");
415 foreach (string str in fileList)
416 {
417 if (str.Trim() == RemoteFileName.Trim())
418 {
419 return true;
420 }
421 }
422 return false;
423 }
424 /// <summary>
425 /// 创建文件夹
426 /// </summary>
427 /// <param name="dirName"></param>
428 public void MakeDir(string dirName)
429 {
430 FtpWebRequest reqFTP;
431 try
432 {
433 // dirName = name of the directory to create.
434 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
435 reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
436 reqFTP.UseBinary = true;
437 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
438 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
439 Stream ftpStream = response.GetResponseStream();
440 ftpStream.Close();
441 response.Close();
442 }
443 catch (Exception ex)
444 {
445 //Insert_Standard_ErrorLog.Insert("FtpWeb", "MakeDir Error --> " + ex.Message);
446 }
447 }
448 /// <summary>
449 /// 创建文件
450 /// </summary>
451 /// <param name="dirName"></param>
452 /// <param name="interfaceLocation"></param>
453 /// <param name="fileName"></param>
454 public string SavaProcess(string fileName, string dirName,string FilePath)
455 {
456
457 //判断路径是否存在
458 if (!System.IO.Directory.Exists(FilePath))
459 {
460 System.IO.Directory.CreateDirectory(FilePath);
461 }
462 //不存在就创建
463 FilePath = FilePath + "//" + fileName ;
464 //文件覆盖方式添加内容
465 System.IO.StreamWriter file = new System.IO.StreamWriter(FilePath, false);
466 //保存数据到文件
467 file.Write(dirName);
468 //关闭文件
469 file.Close();
470 //释放对象
471 file.Dispose();
472 return FilePath;
473 }
474 /// <summary>
475 /// 获取指定文件大小
476 /// </summary>
477 /// <param name="filename"></param>
478 /// <returns></returns>
479 public long GetFileSize(string filename)
480 {
481 FtpWebRequest reqFTP;
482 long fileSize = 0;
483 try
484 {
485 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
486 reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
487 reqFTP.UseBinary = true;
488 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
489 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
490 Stream ftpStream = response.GetResponseStream();
491 fileSize = response.ContentLength;
492 ftpStream.Close();
493 response.Close();
494 }
495 catch (Exception ex)
496 {
497 //Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFileSize Error --> " + ex.Message);
498 }
499 return fileSize;
500 }
501 /// <summary>
502 /// 改名
503 /// </summary>
504 /// <param name="currentFilename"></param>
505 /// <param name="newFilename"></param>
506 public void ReName(string currentFilename, string newFilename)
507 {
508 FtpWebRequest reqFTP;
509 try
510 {
511 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
512 reqFTP.Method = WebRequestMethods.Ftp.Rename;
513 reqFTP.RenameTo = newFilename;
514 reqFTP.UseBinary = true;
515 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
516 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
517 Stream ftpStream = response.GetResponseStream();
518 ftpStream.Close();
519 response.Close();
520 }
521 catch (Exception ex)
522 {
523 //Insert_Standard_ErrorLog.Insert("FtpWeb", "ReName Error --> " + ex.Message);
524 }
525 }
526 /// <summary>
527 /// 移动文件
528 /// </summary>
529 /// <param name="currentFilename"></param>
530 /// <param name="newFilename"></param>
531 public void MovieFile(string currentFilename, string newDirectory)
532 {
533 ReName(currentFilename, newDirectory);
534 }
535 /// <summary>
536 /// 将数据写入文本文件中
537 /// </summary>
538 /// <param name="Filename"></param>
539 /// <param name="FileDate"></param>
540 public void WriteFile(string Filename, string FileDate)
541 {
542 //传入文本文件的名称,并将数据写入到文本文件中。
543 FileStream fs = new FileStream(Filename, FileMode.OpenOrCreate, FileAccess.ReadWrite);
544 StreamWriter sw = new StreamWriter(fs); // 创建写入流
545 sw.WriteLine(FileDate); // 写入数据
546 sw.Close(); //关闭文件
547 Console.WriteLine("OK");
548 Console.ReadKey();
549
550 }
551
552 /// <summary>
553 /// zip压缩文件
554 /// </summary>
555 /// <param name="filename">filename生成的文件的名称,如:C\123\123.zip</param>
556 /// <param name="directory">directory要压缩的文件夹路径</param>
557 /// <returns></returns>
558 public bool PackFiles(string filename, string directory)
559 {
560 try
561 {
562 directory = directory.Replace("/", "\\");
563
564 if (!directory.EndsWith("\\"))
565 directory += "\\";
566 if (!Directory.Exists(directory))
567 {
568 Directory.CreateDirectory(directory);
569 }
570 if (File.Exists(filename))
571 {
572 File.Delete(filename);
573 }
574
575 FastZip fz = new FastZip();
576 fz.CreateEmptyDirectories = true;
577 fz.CreateZip(filename, directory, true, "");
578
579 return true;
580 }
581 catch (Exception)
582 {
583 return false;
584 }
585 }
586
587 /// <summary>
588 /// gzip压缩文件
589 /// </summary>
590 /// <param name="filename">需要进行压缩的文件</param>
591 /// <param name="nowfilename">压缩后的文件的名字</param>
592 /// <returns></returns>
593 public void GPackFiles(string filename, string nowfilename)
594 {
595 using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
596 {
597 //创建写入流
598 using (FileStream save = new FileStream(nowfilename, FileMode.Create, FileAccess.Write))
599 {
600 //创建包含写入流的压缩流
601 using (GZipStream gs = new GZipStream(save, CompressionMode.Compress))
602 {
603 //创建byte[]数组中转数据
604 byte[] b = new byte[1024 * 1024];
605 int count = 0;
606 //循环将读取流中数据写入到byte[]数组中
607 while ((count = fs.Read(b, 0, b.Length)) > 0)
608 {
609 //将byte[]数组中数据写入到压缩流
610 gs.Write(b, 0, b.Length);
611 }
612 }
613 }
614 }
615
616 }
617
618 /// <summary>
619 /// gzip压缩文件
620 /// </summary>
621 /// <param name="filePath">需要进行压缩的文件</param>
622 /// <param name="zipFilePath">压缩后的文件的名字</param>
623 /// <returns></returns>
624 public void gZipFile(string filePath, string zipFilePath)
625 {
626 Stream s = new GZipOutputStream(File.Create(zipFilePath));
627 FileStream fs = File.OpenRead(filePath);
628 int size;
629 byte[] buf = new byte[4096];
630 do
631 {
632 size = fs.Read(buf, 0, buf.Length);
633 s.Write(buf, 0, size);
634 } while (size > 0);
635 s.Close();
636 fs.Close();
637 }
638
639 public string Zip(string value)
640 {
641 //Transform string into byte[]
642 byte[] byteArray = new byte[value.Length];
643 int indexBA = 0;
644 foreach (char item in value.ToCharArray())
645 {
646 byteArray[indexBA++] = (byte)item;
647 }
648 //Prepare for compress
649 System.IO.MemoryStream ms = new System.IO.MemoryStream();
650 System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms,System.IO.Compression.CompressionMode.Compress);
651 //Compress
652 sw.Write(byteArray, 0, byteArray.Length);
653 //Close, DO NOT FLUSH cause bytes will go missing...
654 sw.Close();
655 //Transform byte[] zip data to string
656 byteArray = ms.ToArray();
657 System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
658 foreach (byte item in byteArray)
659 {
660 sB.Append((char)item);
661 }
662 ms.Close();
663 sw.Dispose();
664 ms.Dispose();
665 return sB.ToString();
666 }
667
668 public string Compress(string param)
669 {
670 byte[] data = System.Text.Encoding.UTF8.GetBytes(param);
671 //byte[] data = Convert.FromBase64String(param);
672 MemoryStream ms = new MemoryStream();
673 Stream stream = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(ms);
674 try
675 {
676 stream.Write(data, 0, data.Length);
677 }
678 finally
679 {
680 stream.Close();
681 ms.Close();
682 }
683 return Convert.ToBase64String(ms.ToArray());
684 }
685
686 /// <summary>
687 /// 解压
688 /// </summary>
689 /// <param name="param"></param>
690 /// <returns></returns>
691 public string Decompress(string param)
692 {
693 string commonString = "";
694 byte[] buffer = Convert.FromBase64String(param);
695 MemoryStream ms = new MemoryStream(buffer);
696 Stream sm = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(ms);
697 //这里要指明要读入的格式,要不就有乱码
698 StreamReader reader = new StreamReader(sm, System.Text.Encoding.UTF8);
699 try
700 {
701 commonString = reader.ReadToEnd();
702 }
703 finally
704 {
705 sm.Close();
706 ms.Close();
707 }
708 return commonString;
709 }
710
711 /// <summary>
712 /// tar压缩文件
713 /// </summary>
714 /// <param name="filename">filename生成的文件的名称,如:C\123\123.zip</param>
715 /// <param name="directory">directory要压缩的文件夹路径</param>
716 /// <returns></returns>
717 public void TarCreateFromStream(string filename , string directory)
718 {
719
720 // 创建输出流。不必是磁盘,可以是内存流等。
721 string tarOutFn = filename;
722 Stream outStream = File.Create(tarOutFn);
723 TarOutputStream tarOutputStream = new TarOutputStream(outStream);
724
725 CreateTarArchive(tarOutputStream, directory);
726
727 // 关闭归档文件也关闭底层流。
728 tarOutputStream.Close();
729 }
730
731 private void CreateTarArchive(TarOutputStream tarOutputStream, string sourceDirectory)
732 {
733 // 可选地,为目录本身写一个条目。
734 // TarEntry tarEntry = TarEntry.CreateEntryFromFile(sourceDirectory);
735 // tarOutputStream.PutNextEntry(tarEntry);
736 // 将每个文件写入tar。
737 string[] filenames = Directory.GetFiles(sourceDirectory);
738
739 foreach (string filename in filenames)
740 {
741 using (Stream inputStream = File.OpenRead(filename))
742 {
743 int idxStart = filename.LastIndexOf('\\') + 1;
744 string tarName = filename.Substring(idxStart, filename.Length - idxStart);
745 long fileSize = inputStream.Length;
746 TarEntry entry = TarEntry.CreateTarEntry(tarName);
747
748 // 必须设置大小,否则当输出超过时,TAROutPutsFipe将失败。
749 entry.Size = fileSize;
750
751 // 在写入数据之前,将条目添加到TAR流中。
752 tarOutputStream.PutNextEntry(entry);
753
754 // 这是从TracSovi.Read EngyCype复制的
755 byte[] localBuffer = new byte[32 * 1024];
756 while (true)
757 {
758 int numRead = inputStream.Read(localBuffer, 0, localBuffer.Length);
759 if (numRead <= 0)
760 {
761 break;
762 }
763 tarOutputStream.Write(localBuffer, 0, numRead);
764 }
765 }
766 tarOutputStream.CloseEntry();
767 }
768 // 递归。如果不需要就删除。
769 //string[] directories = Directory.GetDirectories(sourceDirectory);
770 //foreach (string directory in directories)
771 //{
772 // CreateTarArchive(tarOutputStream, directory);
773 //}
774 }
775
776 }
777 }

FTP操作/Passive/Active控制的更多相关文章

  1. C# FTP操作

    using System; using System.Collections.Generic; using System.Net; using System.IO; namespace FTP操作 { ...

  2. ftp的passive模式

    ftp的passive模式 今天在一台测试服务器上搭建ftp,折腾了许久. 主要是不了解ftp的passive模式和port模式的区别.这里记录一下. 和passive模式对应的叫做port模式,也叫 ...

  3. PHP FTP操作类( 上传、拷贝、移动、删除文件/创建目录 )

    /** * 作用:FTP操作类( 拷贝.移动.删除文件/创建目录 ) * 时间:2006/5/9 * 作者:欣然随风 * QQ:276624915 */ class class_ftp { publi ...

  4. Ubantu下FTP服务器资源进行控制

    在FTP服务器的管理中无论对本地用户还是匿名用户,对于FTP服务器资源的使用都需要进行控控制, 避免由于负担过大造成FTP服务器运行异常, 可以添加以下配置项对FTP客户机使用FTP服务器资源进行控制 ...

  5. 关于FTP操作的功能类

    自己在用的FTP类,实现了检查FTP链接以及返回FTP没有反应的情况. public delegate void ShowError(string content, string title); // ...

  6. FtpHelper ftp操作类库

    FtpHelper ftp操作类库 using System; using System.Collections.Generic; using System.Linq; using System.Te ...

  7. Asp.Net Core 2.0 项目实战(11) 基于OnActionExecuting全局过滤器,页面操作权限过滤控制到按钮级

    1.权限管理 权限管理的基本定义:百度百科. 基于<Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员.后台管理员同时登录>我们做过了登录认证, ...

  8. C# FTP操作类的代码

    如下代码是关于C# FTP操作类的代码.using System;using System.Collections.Generic;using System.Text;using System.Net ...

  9. 【转载】C#工具类:FTP操作辅助类FTPHelper

    FTP是一个8位的客户端-服务器协议,能操作任何类型的文件而不需要进一步处理,就像MIME或Unicode一样.可以通过C#中的FtpWebRequest类.NetworkCredential类.We ...

随机推荐

  1. Java中输出小数点后几位

    笔试时候,遇到让你写输出小数点后几位,当时很是头疼,下来后,查了查发现,没什么难的.网上有各种情况都讨论了(一般分为4种),在这里我着重讨论一下比较实用,比较简单,比较方便操作的几种: 1 publi ...

  2. u-boot 移植 --->1、u-boot配置(Kbuild)

    早期的U-BOOT的裁剪是没有使用Kbuild工具的,后来就借鉴了Linux的Kbuild同时也是方便使用者裁剪,因为他的原理和Linux内核的配置裁剪原理是相同的.今天拿来分析的U-Boot的版本是 ...

  3. Python Web Framework All In One

    Python Web Framework All In One Django and Flask are the top Python web frameworks so far. Django ht ...

  4. CSS pseudo element All In One

    CSS pseudo element All In One CSS 伪元素 https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elemen ...

  5. HTML a Tag All In One

    HTML a Tag All In One HTML <a> target https://developer.mozilla.org/en-US/docs/Web/HTML/Elemen ...

  6. console.clear

    console.clear Chrome console.clear && console.clear() refs xgqfrms 2012-2020 www.cnblogs.com ...

  7. useful podcast

    useful podcast front end podcast https://shoptalkshow.com https://stackoverflow.blog/podcast/ SoundC ...

  8. react hooks & component will unmount & useEffect & clear up

    react hooks & component will unmount & useEffect & clear up useEffect & return === u ...

  9. js 实现简单的parseInt和parseFloat

    function myParseInt(str: string): number { let result = NaN; for (let i = 0; i < str.length; i++) ...

  10. NGK公链:在规则明确的环境下运行超级节点机制

    首先要跟大家明确的一点是,21个超级节点是投票选举出来的,并不是系统在创立之初就已经确定好了的.那么相信大家也一定很好奇,这21个超级节点是通过什么方式产生? NGK.IO对分布式超级节点使用了一个自 ...