2015-08-28 158 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 –