2015-08-28 185 views
0

下面的代码在创建zip文件时工作正常,但创建的文件有一个文件夹IIS部署>>> WebService ...然后是文本文件,而不仅仅是文本文件。从多个文件创建zip文件

如何将文本文件添加到zip文件?

ZipFile z = ZipFile.Create("C:\\IIS Deploy\\WebServiceTest\\WebServiceTest\\Accident.zip"); 

//initialize the file so that it can accept updates 
z.BeginUpdate(); 

//add the file to the zip file   
z.Add("C:\\IIS Deploy\\WebServiceTest\\WebServiceTest\\test1.txt"); 
z.Add("C:\\IIS Deploy\\WebServiceTest\\WebServiceTest\\test2.txt"); 
z.Add("C:\\IIS Deploy\\WebServiceTest\\WebServiceTest\\test3.txt"); 

//commit the update once we are done 
z.CommitUpdate(); 
//close the file 
z.Close(); 
+0

如果我正确理解你的问题,我认为解决的办法可能是创建压缩文件,并添加内容,而不一个完全合格的路径。可能还有一个选项可以在Add方法上添加文件(不考虑其包含的路径)。 –

+0

我试过并得到文件错误..应该指定路径我猜 –

+0

我认为@codebased答案中提供的解决方案是一个很好的路径。 –

回答

1

如果您拥有同一文件夹中的所有内容,那么最简单的选择是使用CreateFromDirectory类。

static void Main() 
    { 
    // Create a ZIP file from the directory "source". 
    // ... The "source" folder is in the same directory as this program. 
    // ... Use optimal compression. 
    ZipFile.CreateFromDirectory("source", "destination.zip", 
     CompressionLevel.Optimal, false); 

    // Extract the directory we just created. 
    // ... Store the results in a new folder called "destination". 
    // ... The new folder must not exist. 
    ZipFile.ExtractToDirectory("destination.zip", "destination"); 
    } 

http://www.dotnetperls.com/zipfile

请注意,它是适用于.NET框架4.6和4.5

+0

我正在使用ICSharpCode.SharpZipLib.Zip –