使用C#压缩单个文件 [英] Compress a single file using C#

查看:497
本文介绍了使用C#压缩单个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用.NET 4.5,如果我试图压缩了CreateFromDirectory整个目录zip文件类的伟大工程。不过,我只想拉链拉上一个文件目录。我试图指向一个特定的文件(folder\data.txt),但不起作用。我认为ZipArchive类,因为它有一个CreateEntryFromFile的方法,但似乎这只是允许您创建一个进入现有文件。



有没有办法简单地压缩了一个文件,而无需创建一个空的压缩文件(里面有它的问题),然后使用ZipArchiveExtension的CreateEntryFromFile的方法?



**这也是假设我在不能使用第三方的时刻附加一个企业计划工作。



例如,从: http://msdn.microsoft.com/en -us /库/ ms404280%28V = vs.110%29.aspx

 字符串startPath = @C :\example\start; 
串zipPath = @C:\example\result.zip
串extractPath = @C:\example\extract

ZipFile.CreateFromDirectory(startPath,zipPath);

ZipFile.ExtractToDirectory(zipPath,extractPath);



但如果startPath分别为 @C:\example\ start\myFile.txt;,它会抛出一个错误,该目录是无效的。


解决方案
< 。p>要得到这个工作,最简单的方法是使用一个临时文件夹



有关荏苒:




  1. 创建一个临时文件夹

  2. 将文件夹

  3. 邮编文件夹

  4. 删除文件夹



有关解压:




  1. 解压档案

  2. 从临时文件夹移动文件到您的位置

  3. 删除临时文件夹


I am using .NET 4.5, and the ZipFile class works great if I am trying to zip up an entire directory with "CreateFromDirectory". However, I only want to zip up one file in the directory. I tried pointing to a specific file (folder\data.txt), but that doesn't work. I considered the ZipArchive class since it has a "CreateEntryFromFile" method, but it seems this only allows you to create an entry into an existing file.

Is there no way to simply zip up one file without creating an empty zipfile (which has its issues) and then using the ZipArchiveExtension's "CreateEntryFromFile" method?

**This is also assuming I am working on a company program which cannot use third-party add-ons at the moment.

example from:http://msdn.microsoft.com/en-us/library/ms404280%28v=vs.110%29.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);

But if startPath were to be @"c:\example\start\myFile.txt;", it would throw an error that the directory is invalid.

解决方案

The simplest way to get this working is to use a temporary folder.

FOR ZIPPING:

  1. Create a temp folder
  2. Move file to folder
  3. Zip folder
  4. Delete folder

FOR UNZIPPING:

  1. Unzip archive
  2. Move file from temp folder to your location
  3. Delete temp folder

这篇关于使用C#压缩单个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆