2015-01-12 6 views
0

Я сделал следующее, но я не вижу zip-файл в directroy. C#Как сохранить .zip в папку с помощью ZipArchive?

public static void AddToZip(string fileToAdd, string directory) 
    { 
     string entryName = fileToAdd.Replace(directory, string.Empty); 
     string archiveName = entryName.Replace(Path.GetExtension(entryName), ".zip"); 

     using (ZipArchive za = ZipFile.Open(archiveName, ZipArchiveMode.Create)) 
     { 
      za.CreateEntryFromFile(fileToAdd, entryName, CompressionLevel.Optimal); 
     } 
    } 

и это ссылка, за которой я следовал. http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive(v=vs.110).aspx

+2

Это венгерское обозначение, которое вы используете? – dcastro

+1

Что такое 'sArchiveName', когда вы открываете ZipFile? –

+0

у вас возникли какие-либо ошибки? – faby

ответ

0

Наконец-то он работал после некоторых проб и ошибок.

public static void AddToZip(string fileToAdd, string directory) 
    { 
     string entryName = fileToAdd.Replace(directory, string.Empty);//name of the file inside zip archive 
     string tempDir = Path.Combine(directory, Path.GetFileNameWithoutExtension(entryName)); 

     if (Directory.Exists(tempDir)) DeleteDirector(tempDir); 
     else Directory.CreateDirectory(tempDir); 

     System.IO.File.Move(fileToAdd, Path.Combine(tempDir, entryName));//as the CreateFromDirectoy add all the file from the directory provided, we are moving our file to temp dir. 

     string archiveName = entryName.Replace(Path.GetExtension(entryName), ".zip"); //name of the zip file. 

     ZipFile.CreateFromDirectory(tempDir, Path.Combine(directory, archiveName)); 
     DeleteDirector(tempDir); 
    } 
    private static void DeleteDirector(string deletedir) 
    { 
     foreach (string file in Directory.GetFiles(deletedir)) 
     { 
      System.IO.File.Delete(file); 
     } 
     Directory.Delete(deletedir); 
    } 

Я знаю, что это не лучшее решение. поэтому, вы можете изменить/улучшить его.

Смежные вопросы