본문 바로가기
프로그래밍/C#

[C#] zip 파일로 폴더/파일 압축 및 압축 해제

by 왕초보 개발자 2021. 3. 29.
728x90

폴더 내 파일 압축하기

String startPath = @"C:\test"; // 압축할 폴더 경로
String zipPath = @"C:\test.zip";   // 압축된 파일 경로 & 파일명

System.IO.FileInfo fi = new System.IO.FileInfo(zipPath);

if (!fi.Exists){
	System.IO.Compression.ZipFile.CreateFromDirectory(startPath, zipPath); // 파일 압축하여 저장하기
}

 

다수의 파일 압축하기

// 압축할 파일들의 배열
String[] files = {@"C:\example.txt", @"C:\example2.txt"}; 
// 새로운 zip파일을 생성하고 Open하기 
String zipPath = @"C:\test.zip";
var zip = ZipFile.Open(zipPath, ZipArchiveMode.Create);

foreach (var file in files){
    // zip파일 안에 배열 내 파일들을 집어넣기
    zip.CreateEntryFromFile(file, System.IO.Path.GetFileName(file), CompressionLevel.Optimal);
}

// zip 객체를 삭제
zip.Dispose();

 

압축 해제하기

String zipPath = @"C:\test.zip";      // zip 파일 경로
String extractPath = @"C:\test";  // 압축 해제할 폴더 경로

System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, extractPath);
728x90