Microsoft .NET/C#
                
              [C#] 폴더 압축 / 다중 파일 압축 / 압축 해제
                전자기린
                 2020. 1. 6. 15:57
              
              
            
            1. 폴더 압축
//폴더 압축
string folderPath = folderSelectorDialog.FileName;
string savePath = folderSelectorDialog.FileName + ".zip";
System.IO.Compression.ZipFile.CreateFromDirectory(folderPath, savePath);
2. 다중 파일 압축
private void btnCompress_Multiple_Click(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog() { Multiselect = true};
    if (ofd.ShowDialog() == true)
    { 
        FileCompression_Multiple(ofd.FileNames);
    }
}
public bool FileCompression_Multiple(string[] files)
{
    //예외처리
    if (files == null)      return false;
    if (files.Length == 0)  return false;
    FileInfo fi = new FileInfo(files[0]);
    string parentFolderPath = fi.DirectoryName;
    string tempFolderName = fi.Name.Split('.')[0];
    DirectoryInfo di = new DirectoryInfo(parentFolderPath + "\\" + tempFolderName);
    //첫번째 파일의 명을 가지고 폴더를 생성하므로 동일한 폴더가 없는지 체크 후 압축함.
    if (di.Exists == false)
    {
        //폴더 생성
        di.Create();
        //선택 파일 폴더로 이동
        foreach (var filePath in files)
        {
            FileInfo f = new FileInfo(filePath);
            System.IO.File.Copy(filePath, di.FullName + "\\" + f.Name);
        }
        //폴더 압축
        System.IO.Compression.ZipFile.CreateFromDirectory(di.FullName, di.FullName+".zip");
        //임시 생성 폴더 삭제
        di.Delete(true);
        return true;
    }
    return false;
}
3. 압축 해제
//압축 해제
System.IO.Compression.ZipFile.ExtractToDirectory(cofd.FileName, cofd.FileName.Replace(".zip", ""));