본문 바로가기

C#

복수 파일을 선택해서 압축파일을 만들기

반응형

C#에서 zip 압축 파일을 만드는 방법은 System.IO.Compression 네임스페이스의 ZipFile 클래스를 사용하는 것입니다.

 

 

ZipFile 클래스 (System.IO.Compression)

zip 보관 위치 만들기, 추출 및 열기를 위한 정적 메서드를 제공합니다.

learn.microsoft.com

먼저 사용자로부터 압축 파일명과 압축할 파일을 복수 선택할 수 있는 기능을 제공해야 합니다.

압축 파일명을 사용자에게 입력받는 방법은 OpenFileDialog를 사용하여 파일 대화 상자를 열고, 사용자가 입력한 파일명을 가져오는 것입니다.

 

 

OpenFileDialog 클래스 (System.Windows.Forms)

사용자가 파일을 열도록 요청하는 표준 대화 상자를 표시합니다. 이 클래스는 상속될 수 없습니다.

learn.microsoft.com

코드로 구현하면 아래와 같습니다.

string zipFileName;
using (var dialog = new SaveFileDialog())
{
    dialog.Filter = "ZIP 파일 (*.zip)|*.zip";
    dialog.Title = "압축 파일 저장";
    if (dialog.ShowDialog() == DialogResult.OK)
    {
        zipFileName = dialog.FileName;
    }
    else
    {
        return; // 사용자가 취소하면 종료
    }
}

그 다음, 압축할 파일을 복수 선택할 수 있도록 하기 위해서는 OpenFileDialog의 Multiselect 속성을 true로 설정합니다.

using (var dialog = new OpenFileDialog())
{
    dialog.Filter = "모든 파일 (*.*)|*.*";
    dialog.Title = "압축할 파일 선택";
    dialog.Multiselect = true;
    if (dialog.ShowDialog() == DialogResult.OK)
    {
        // 선택된 파일들을 압축
        foreach (string file in dialog.FileNames)
        {
            // <생략>
        }
    }
    else
    {
        return; // 사용자가 취소하면 종료
    }
}

이제 선택된 파일들을 ZipFile.CreateFromDirectory() 메서드를 사용하여 압축하면 됩니다. 

이 메서드는 지정된 디렉토리에 있는 파일을 지정된 zip 파일에 압축합니다.

ZipFile.CreateFromDirectory(sourceDirectoryName, zipFileName);

이를 통해 사용자가 선택한 파일들이 지정된 압축 파일명으로 압축됩니다.

이후 생성된 압축 파일을 사용자에게 제공하면 됩니다.

 

이를 응용해서 아래와같은 코드를 만들어볼수 있습니다.

using System;
using System.IO;
using System.IO.Compression;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        // 파일을 복수 선택하기 위한 OpenFileDialog 생성
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Multiselect = true;
        openFileDialog.Title = "압축할 파일을 선택하세요";
        
        // 사용자가 파일을 선택하고 OK를 누르면
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            // 압축 파일명 입력을 위한 InputBox 생성
            string zipFileName = Microsoft.VisualBasic.Interaction.InputBox("파일명:", "Zip FileName", "샘플.zip");

            // Zip 파일 생성
            CreateZipFile(zipFileName, openFileDialog.FileNames);
            
            Console.WriteLine("파일압축이 완료되었습니다.");
        }
    }

    static void CreateZipFile(string zipFileName, string[] files)
    {
        // Zip 파일 생성
        using (FileStream zipToCreate = new FileStream(zipFileName, FileMode.Create))
        {
            using (ZipArchive archive = new ZipArchive(zipToCreate, ZipArchiveMode.Create))
            {
                // 선택한 각 파일을 압축 파일에 추가
                foreach (string file in files)
                {
                    // 파일의 상대 경로 추출
                    string entryName = Path.GetFileName(file);
                    
                    // Zip 파일 내에 새 엔트리 생성
                    ZipArchiveEntry entry = archive.CreateEntry(entryName);

                    // 파일을 엔트리에 복사
                    using (FileStream fileToCompress = new FileStream(file, FileMode.Open))
                    {
                        using (Stream zipEntryStream = entry.Open())
                        {
                            fileToCompress.CopyTo(zipEntryStream);
                        }
                    }
                }
            }
        }
    }
}
반응형