2017-02-10 1 views
1

나는 여러 폴더가 있고 각 폴더에는 파일 수가 있습니다. 다른 폴더에서 파일 경로를 가져 오는 중입니다. 이러한 파일을 단일 zip 파일로 압축해야합니다.C# - 파일 경로 목록에서

나는 하나의 폴더에 파일이있는 경우, 내가

string startPath = @"c:\example\start";//folder to add 
string zipPath = @"c:\example\result.zip";//URL for your ZIP file 
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true); 
string extractPath = @"c:\example\extract";//path to extract 
ZipFile.ExtractToDirectory(zipPath, extractPath); 
using (ZipArchive newFile = ZipFile.Open(zipName, ZipArchiveMode.Create)) 
{ 
    foreach (string file in Directory.GetFiles(myPath)) 
    { 
     newFile.CreateEntryFromFile(file); 
    } 
} 

내가 폴더 모르는 가정하자, 나는 전용 파일의 경로 목록을 사용하여 압축을 할 수있는, 내가 통해 foreach는 필요 각 파일 경로와 우편 번호에 추가하십시오. 이 일을 어떻게해야합니까?

답변

2

당신은 디렉토리에있는 모든 파일을 열거 할 수는 Directory.GetFiles 오버로드와 SearchOption.AllDirectories 옵션으로 서브 디렉토리를 포함하고는

String[] allfiles = System.IO.Directory.GetFiles("myPath", "*.*", System.IO.SearchOption.AllDirectories); 
foreach (string file in allfiles) 
{ 
    newFile.CreateEntryFromFile(file); 
} 

당신은 너무 한 번에 아카이브를 만들 ZipFile.CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName) 또는 과부하를 사용할 수 있습니다 사용합니다.

또한 Path.GetDirectoryName() 방법을 통해 더 유연하게 zip 아카이브 구조를 조작 할 수있는 방법이 있습니다. 단지 있는지 여부를 확인,

using (ZipFile zip = new ZipFile()) 
{ 
    zip.AddFiles(files); 
    zip.Save("Archive.zip"); 
} 
+0

이 아니 하위 directries에 대한 일을하거나하지 않습니다 나는 어떻게 지퍼를 만들 수 있을까? –

+0

@hildasonica는 yor 문제를 이해할 수 없습니다. [CreateEntryFromFile] (https://msdn.microsoft.com/en-us/library/hh485720(v=vs.110) .aspx)은 두 번째 매개 변수로 아카이브의 파일 이름을 조작 할 수 있습니다. 폴더 구조의 복사본이 필요한 경우 원한다면 소스 파일 pathes를 무시하거나 무시할 수 있습니다. –

+0

위의 코드에서 GetFiles라는 메서드를 사용하여 paricular 폴더에서 모든 파일을 가져옵니다. 제 경우에는 데이터베이스에서 가져올 파일 경로 목록을 갖게됩니다. 그 파일 경로 (또는 fieurl)를 사용하여 우편 번호를 만들 필요가 있습니다. 여기 GetFiles() 메서드를 사용할 수 없다고 생각합니다. –

1

newget 관리자에서 DotNetZip 라이브러리를 사용하여 마지막으로

foreach(var filePath in files) 
{ 
    var directory = Path.GetDirectoryName(filePath); 
    var fileName = Path.GetFileName(filePath); 
    var entry = archive.GetEntryFromFile(filePath, $"{directory}/{fileName}"); 
} 

, 당신이 제 3 자 라이브러리 DotNetZip을 사용하고 불과 3 코드의 라인을 yor 시나리오를 해결할 수 있습니다 : 여기에 예입니다 그것은 단지 당신이 배열에서 [ "\ 폴더 1 \ auditnew.JPG", "\ Folder2와 \ audi.JPG"]와 같은 filepaths의 배열을하자,

using (ZipFile zip = new ZipFile()) 
{ 
    foreach(var filestring in AllFileArray) 
    { 
     zip.AddFile(filestring); 
    } 
    zip.save("MyZipFile.zip") 
}