2008-10-13 4 views
13

SharpZipLib 라이브러리를 사용하여 다음 코드를 사용하여 .zip 파일에 파일을 추가하지만 각 파일은 전체 경로와 함께 저장됩니다. .zip 파일의 '루트'에만 파일을 저장해야합니다.SharpLibZip : 경로가없는 파일 추가

string[] files = Directory.GetFiles(folderPath); 
using (ZipFile zipFile = ZipFile.Create(zipFilePath)) 
{ 
    zipFile.BeginUpdate(); 
    foreach (string file in files) 
    { 
      zipFile.Add(file); 
    } 
    zipFile.CommitUpdate(); 
} 

제공되는 설명서에서이 옵션에 대해 아무것도 찾을 수 없습니다. 이것은 매우 인기있는 도서관이므로,이 책을 읽은 누군가가 뭔가를 알고 있기를 바랍니다.

답변

21

내 솔루션은 NameTransform 객체의 속성을 설정하는 것이었다 다음 SharpZipLib 문서에 따르면

public void Add(string fileName, string entryName) 
Parameters: 
    fileName(String) The name of the file to add. 
    entryName (String) The name to use for the ZipEntry on the Zip file created. 

이 방법을 시도, Add 메서드의 오버로드가 ZipFileZipNameTransform이고 TrimPrefix은 파일의 디렉토리로 설정됩니다. 이로 인해 전체 파일 경로 인 항목 이름의 디렉토리 부분이 제거됩니다. 멋진 무엇

public static void ZipFolderContents(string folderPath, string zipFilePath) 
{ 
    string[] files = Directory.GetFiles(folderPath); 
    using (ZipFile zipFile = ZipFile.Create(zipFilePath)) 
    { 
     zipFile.NameTransform = new ZipNameTransform(folderPath); 
     foreach (string file in files) 
     { 
      zipFile.BeginUpdate(); 
      zipFile.Add(file); 
      zipFile.CommitUpdate(); 
     } 
    } 
} 

는하여 NameTransform 속성 이름의 사용자 정의는 변환 수, 유형 INameTransform의입니다.

+1

완벽 하군요, 제가 찾고 있던 바로 그 겁니다. 감사! –

+0

네, 여기와 같습니다. 정확히 내가 필요한 것. 감사! –

+0

고마워. 많은 어려움 끝에 나는 나의 문제를 해결할 수 있었다. – Dilip0165

10

System.IO.Path.GetFileName()을 ZipFile.Add()의 entryName 매개 변수와 결합하면 어떨까요?

string[] files = Directory.GetFiles(folderPath); 
using (ZipFile zipFile = ZipFile.Create(zipFilePath)) 
{ 
    zipFile.BeginUpdate(); 
    foreach (string file in files) 
    { 
      zipFile.Add(file, System.IO.Path.GetFileName(file)); 
    } 
    zipFile.CommitUpdate(); 
} 
+1

이름으로 파일을 추가 할 때 ZipFile.Add()에 대한 entryName 매개 변수에 오버로드가 없지만 사용자의 생각을 좋아합니다. 아래 내 대답을 참조하십시오. – ProfK

+2

최신 버전의 라이브러리가 있습니까? 그것은 file.add에 과부하가있다 – rjrapson

+2

나는 적어도 거기에 최신 버전에서 적어도 확신합니다. –

3

Directory.GetFiles()에 대한 MSDN 항목은 반환되는 파일 이름이 제공된 경로 매개 변수에 추가되는 것을 말한다. (http://msdn.microsoft.com/en-us/library/07wt70x2.aspx)이므로 zipFile.Add()에 전달할 문자열에 경로가 포함되어 있습니다.

string[] files = Directory.GetFiles(folderPath); 
using (ZipFile zipFile = ZipFile.Create(zipFilePath)) 
{ 
    zipFile.BeginUpdate(); 
    foreach (string file in files) 
    { 
      zipFile.Add(file, Path.GetFileName(file)); 
    } 
    zipFile.CommitUpdate(); 
} 
+1

예, 추가 할 파일 경로에서 디렉터리를 제외하면 Add 메서드는 파일을 찾지 않습니다. 아래 내 대답을 참조하십시오. – ProfK