因为做机床参数导入导出功能需要对文件进行压缩与解压,对文件压缩解压的方法进行整理。


###一 .net自带方法

####1.GZipStream类
命名空间:System.IO.Compression,自.net FrameWork 2.0起可用。只能压缩、解压文件,不能压缩文件夹。压缩后扩展名为.gz,
可以使用许多常用的压缩工具进行解压缩; 但是,此类本身不提供用于添加文件到或从 zip 存档中提取文件的功能。
网址:https://msdn.microsoft.com/zh-cn/library/system.io.compression.gzipstream(v=vs.110).aspx

**实例**

        public static void Compress(DirectoryInfo directorySelected)
        {
            foreach (FileInfo fileToCompress in directorySelected.GetFiles())
            {
                using (FileStream originalFileStream = fileToCompress.OpenRead())
                {
                    if ((File.GetAttributes(fileToCompress.FullName) & 
                       	FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
                    {
                        using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
                        {
                            using (GZipStream compressionStream = new GZipStream(compressedFileStream, 
                               	CompressionMode.Compress))
                            {
                                originalFileStream.CopyTo(compressionStream);
                            }
                        }

                        FileInfo info = new FileInfo(directoryPath + "\\" + fileToCompress.Name + ".gz");
                        Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                        fileToCompress.Name, fileToCompress.Length.ToString(), info.Length.ToString());
                    }
                }
            }
        }

        public static void Decompress(FileInfo fileToDecompress)
        {
            using (FileStream originalFileStream = fileToDecompress.OpenRead())
            {
                string currentFileName = fileToDecompress.FullName;
                string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);
                using (FileStream decompressedFileStream = File.Create(newFileName))
                {
                    using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                    {
                        decompressionStream.CopyTo(decompressedFileStream);
                        Console.WriteLine("Decompressed: {0}", fileToDecompress.Name);
                    }
                }
            }
        }


####2.ZipPackage 类
命名空间:System.IO.Packaging,自.net FrameWork 3.0 起可用。可以压缩文件与文件夹,压缩后会在压缩文件中产生一个[Content.Types].xml的文件,用于描述该压缩文件的关系。
不可删除,否则将打不开该压缩文件。
网址:https://msdn.microsoft.com/zh-cn/library/system.io.packaging.zippackage(v=vs.110).aspx

**实例**

		private void CreatePackage()
        {
            string documentPath = "D:\\新建文件夹\\1.xml";
            string packagePath = "D:\\33";
            Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(documentPath, UriKind.Relative));
            using (Package package = Package.Open(packagePath, FileMode.Create))
            {
                PackagePart packagePartDocument = package.CreatePart(partUriDocument,System.Net.Mime.MediaTypeNames.Text.Xml);
                using (FileStream fileStream = new FileStream(documentPath, FileMode.Open, FileAccess.Read))
                {
                    CopyStream(fileStream, packagePartDocument.GetStream());
                }
            }
        }

        private static void CopyStream(Stream source, Stream target)
        {
            const int bufSize = 0x1000;
            byte[] buf = new byte[bufSize];
            int bytesRead = 0;
            while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
                target.Write(buf, 0, bytesRead);
        }

####3.ZipFile 类
命名空间:System.IO.Compression,自.net FrameWork 4.5 起可用。
若要使用ZipFile类,必须添加引用System.IO.Compression.FileSystem,否则将编译错误。
可以创建、解压缩、打开zip文档。只能压缩和解压缩文件夹,不能压缩解压单独的文件。可以将文件压缩添加到已存在的压缩包中。

网址:https://msdn.microsoft.com/zh-cn/library/system.io.compression.zipfile(v=vs.110).aspx

**实例**

		//压缩文件目录与解压
        string startPath = @"c:\example\start";
        string zipPath = @"c:\example\result.zip";
        string extractPath = @"c:\example\extract";
        ZipFile.CreateFromDirectory(startPath, zipPath);
        ZipFile.ExtractToDirectory(zipPath, extractPath);

		//文件压缩添加到已存在的压缩包
		string zipPath = @"c:\users\exampleuser\start.zip";
        string newFile = @"c:\users\exampleuser\NewFile.txt";
        using (ZipArchive archive = ZipFile.Open(zipPath, ZipArchiveMode.Update))
        {
            archive.CreateEntryFromFile(newFile, "NewEntry.txt");
        } 
 
###二 第三方类库

####ICSharpCode.SharpZipLib
支持压缩和解压的文件库,支持zip、tar、gzip、lzw格式。
网址:https://icsharpcode.github.io/SharpZipLib/help/api/index.html

**实例**

**使用FastZip快速压缩目录,只能压缩文件夹**

		ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
		zip.CreateZip(fileName, filePath, true, null);

**使用FastZip快速解压目录**

		ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
		zip.ExtractZip(fileName, filePath, null);


**使用ZipOutputStream创建一个压缩包并往里面写入一个文件**

		using (ZipOutputStream s = new ZipOutputStream(File.Create(@"D:\123.zip")))
        {
            s.SetLevel(6);  //设置压缩等级,等级越高压缩效果越明显,但占用CPU也会更多
			using (FileStream fs = File.OpenRead(@"D:\1.txt"))
            {
                byte[] buffer = new byte[4 * 1024];  //缓冲区,每次操作大小
                ZipEntry entry = new ZipEntry(Path.GetFileName(@"改名.txt"));     //创建压缩包内的文件
                entry.DateTime = DateTime.Now;  //文件创建时间
                s.PutNextEntry(entry);          //将文件写入压缩包
                
                int sourceBytes;
                do
                {
                    sourceBytes = fs.Read(buffer, 0, buffer.Length);    //读取文件内容(1次读4M,写4M)
                    s.Write(buffer, 0, sourceBytes);                    //将文件内容写入压缩相应的文件
                } while (sourceBytes > 0);
            }

            s.CloseEntry();
        }
            
        Console.ReadKey();


**使用ZipOutputStream压缩文件夹**

		class Program
    	{
        	static void Main(string[] args)
        	{
            	string Source = @"D:\test";
            	string TartgetFile = @"D:\test.zip";
            	Directory.CreateDirectory(Path.GetDirectoryName(TartgetFile));
            	using (ZipOutputStream s = new ZipOutputStream(File.Create(TartgetFile)))
            	{
                	s.SetLevel(6);
                	Compress(Source, s);
                	s.Finish();
                	s.Close();
            	}
            
            	Console.ReadKey();
        	}

        	/// <summary>
        	/// 压缩
        	/// </summary>
        	/// <param name="source">源目录</param>
        	/// <param name="s">ZipOutputStream对象</param>
        	public static void Compress(string source, ZipOutputStream s)
        	{
            	string[] filenames = Directory.GetFileSystemEntries(source);
            	foreach (string file in filenames)
            	{
                	if (Directory.Exists(file))
                	{
                    	Compress(file, s);  //递归压缩子文件夹
                	}
                	else
                	{
                    	using (FileStream fs = File.OpenRead(file))
                    	{
                        	byte[] buffer = new byte[4 * 1024];
                        	ZipEntry entry = new ZipEntry(file.Replace(Path.GetPathRoot(file),""));     //此处去掉盘符,如D:\123\1.txt 去掉D:
                        	entry.DateTime = DateTime.Now;
                        	s.PutNextEntry(entry);
                        
                        	int sourceBytes;
                        	do
                        	{
                            	sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            	s.Write(buffer, 0, sourceBytes);
                        	} while (sourceBytes > 0);
                    	}
                	}
            	}
        	}
    	}
**使用ZipOutputStream解压文件夹**

		/// <summary>
        /// 解压缩
        /// </summary>
        /// <param name="sourceFile">源文件</param>
        /// <param name="targetPath">目标路经</param>
        public bool Decompress(string sourceFile, string targetPath)
        {
            if (!File.Exists(sourceFile))
            {
                throw new FileNotFoundException(string.Format("未能找到文件 '{0}' ", sourceFile));
            }
            if (!Directory.Exists(targetPath))
            {
                Directory.CreateDirectory(targetPath); 
            }
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourceFile)))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directorName = Path.Combine(targetPath, Path.GetDirectoryName(theEntry.Name));
                    string fileName = Path.Combine(directorName, Path.GetFileName(theEntry.Name));
                    // 创建目录
                    if (directorName.Length > 0)
                    {
                        Directory.CreateDirectory(directorName);
                    }
                    if (fileName != string.Empty)
                    {
                        using (FileStream streamWriter = File.Create(fileName))
                        {
                            int size = 4096;
                            byte[] data = new byte[ 4 * 1024];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else break;
                            }
                        }
                    }
                }
            }
            return true;
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值