时间:2021-05-20
本文实例讲述了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.Replace(sourcepath,copytopath)); foreach (FileSystemInfo nextatom in directory.GetFileSystemInfos()) Folders.Enqueue(nextatom); } else { string sourcefilename = sourcefile.FullName; string zipfilename = sourcefile.FullName.Replace(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#程序设计有所帮助。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了C#编程实现获取文件夹中所有文件的文件名。分享给大家供大家参考,具体如下:想实现这样一个功能:批量修改一个目录所有jpg文件的文件名,在其原始基础
本文实例讲述了C#简单遍历指定文件夹中所有文件的方法。分享给大家供大家参考,具体如下:C#遍历指定文件夹中的所有文件:DirectoryInfoTheFolde
本文实例讲述了python自动zip压缩目录的方法。分享给大家供大家参考。具体实现方法如下:这段代码来压缩数据库备份文件,没有使用python内置的zip模块,
实现的功能:在win7下,每天晚上1点,自动将F:/data中所有文件进行压缩,以[mongodb+日期]命名,将压缩好的文件存储在本地目录F:\MongoDb
本文实例讲述了C#实现的文件压缩和解压缩类。分享给大家供大家参考。具体分析如下:这个C#代码包含了几个类,封装了文件压缩和解压缩常用的方法,包括直接通过代码进行