程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#完成Zip緊縮目次中一切文件的辦法

C#完成Zip緊縮目次中一切文件的辦法

編輯:C#入門知識

C#完成Zip緊縮目次中一切文件的辦法。本站提示廣大學習愛好者:(C#完成Zip緊縮目次中一切文件的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成Zip緊縮目次中一切文件的辦法正文


本文實例講述了C#完成Zip緊縮目次中一切文件的辦法。分享給年夜家供年夜家參考。詳細完成辦法以下:

using System;
using System.IO;
using System.Collections;
using System.IO.Compression;
using System.Collections.Generic;
class FolderZip
{
private const long BUFFER_SIZE = 20480;
static void main(string[] args)
{
string sourcepath=@"C:\tmp";
Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(new DirectoryInfo(sourcepath).GetFileSystemInfos());
string copytopath = @"D:\temp";
copytopath = (copytopath.LastIndexOf(Path.DirectorySeparatorChar) == copytopath.Length - 1) ? copytopath : copytopath+Path.DirectorySeparatorChar + Path.GetFileName(sourcepath);
Directory.CreateDirectory(copytopath);
while (Folders.Count > 0)
{
 FileSystemInfo atom = Folders.Dequeue();
 FileInfo sourcefile = atom as FileInfo;
 if (sourcefile == null)
 {
  DirectoryInfo directory = atom as DirectoryInfo;
  Directory.CreateDirectory(directory.FullName.WordStr(sourcepath,copytopath));
  foreach (FileSystemInfo nextatom in directory.GetFileSystemInfos())
  Folders.Enqueue(nextatom);
 }
 else
 {
  string sourcefilename = sourcefile.FullName;
  string zipfilename = sourcefile.FullName.WordStr(sourcepath,copytopath) + ".zip";
  if (!File.Exists(zipfilename))
  {
   FileStream sourceStream = null;
   FileStream destinationStream = null;
   GZipStream compressedStream = null;
   try
   {
    // Read the bytes from the source file into a byte array
    sourceStream = new FileStream(sourcefilename, FileMode.Open, FileAccess.Read, FileShare.Read);
    // Open the FileStream to write to
    destinationStream = new FileStream(zipfilename, FileMode.OpenOrCreate, FileAccess.Write);
    // Create a compression stream pointing to the destiantion stream
    compressedStream = new DeflateStream(destinationStream, CompressionMode.Compress, true);
    long bufferSize = sourceStream.Length < BUFFER_SIZE ? sourceStream.Length : BUFFER_SIZE;
    byte[] buffer = new byte[bufferSize];
    int bytesRead = 0;
    long bytesWritten = 0;
    while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) != 0)
    {
     compressedStream.Write(buffer, 0, bytesRead);
     bytesWritten += bufferSize;
    }
   }
   catch (ApplicationException)
   {
    continue;
   }
   finally
   {
    // Make sure we allways close all streams
    if (sourceStream != null) sourceStream.Close();
    if (compressedStream != null) compressedStream.Close();
    if (destinationStream != null) destinationStream.Close();
   }
  }
 }
}
}
}

願望本文所述對年夜家的C#法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved