program story

C #의 Zip 폴더

inputbox 2020. 11. 16. 08:14
반응형

C #의 Zip 폴더


C #에서 폴더를 압축하는 방법의 예 (간단한 코드)는 무엇입니까?


최신 정보:

네임 스페이스가 보이지 않습니다 ICSharpCode. 다운로드 ICSharpCode.SharpZipLib.dll했지만 해당 DLL 파일을 어디에 복사해야할지 모르겠습니다. 이 네임 스페이스를 보려면 어떻게해야합니까?

모든 MSDN을 읽었지만 아무것도 찾을 수 없었기 때문에 압축 폴더에 대한 MSDN 예제에 대한 링크가 있습니까?


알겠습니다. 다음 정보가 필요합니다.

ICSharpCode.SharpZipLib.dllVisual Studio에서 해당 네임 스페이스를 보려면 어디에 복사해야 합니까?


이 대답은 .NET 4.5에서 변경됩니다. zip 파일을 만드는 것은 매우 쉽습니다 . 타사 라이브러리가 필요하지 않습니다.

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";

ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);

로부터 DotNetZip의 도움말 파일, http://dotnetzip.codeplex.com/releases/

using (ZipFile zip = new ZipFile())
{
   zip.UseUnicodeAsNecessary= true;  // utf-8
   zip.AddDirectory(@"MyDocuments\ProjectX");
   zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G") ; 
   zip.Save(pathToSaveZipFile);
}

BCL에는이 작업을 수행 할 수있는 것이 없지만 기능을 지원하는 .NET 용 두 가지 훌륭한 라이브러리가 있습니다.

두 가지를 모두 사용해 보았고 두 가지가 매우 완전하고 잘 설계된 API를 가지고 있다고 말할 수 있으므로 주로 개인적인 취향의 문제입니다.

개별 파일을 zip 파일에 추가하는 것이 아니라 폴더 추가를 명시 적으로 지원하는지 여부는 확실하지 않지만 DirectoryInfoFileInfo클래스를 사용하여 디렉터리와 하위 디렉터리에 대해 반복적으로 반복되는 항목을 만드는 것은 매우 쉽습니다 .


.NET 4.5에서 ZipFile.CreateFromDirectory (startPath, zipPath); 방법은 여러 파일과 하위 폴더를 폴더에 넣지 않고 압축하려는 시나리오를 다루지 않습니다. 압축을 풀고 현재 폴더에 파일을 직접 넣으려는 경우에 유효합니다.

이 코드는 나를 위해 일했습니다.

public static class FileExtensions
{
    public static IEnumerable<FileSystemInfo> AllFilesAndFolders(this DirectoryInfo dir)
    {
        foreach (var f in dir.GetFiles())
            yield return f;
        foreach (var d in dir.GetDirectories())
        {
            yield return d;
            foreach (var o in AllFilesAndFolders(d))
                yield return o;
        }
    }
}

void Test()
{
    DirectoryInfo from = new DirectoryInfo(@"C:\Test");
    using (FileStream zipToOpen = new FileStream(@"Test.zip", FileMode.Create))
    {
        using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
        {
            foreach (FileInfo file in from.AllFilesAndFolders().Where(o => o is FileInfo).Cast<FileInfo>())
            {
                var relPath = file.FullName.Substring(from.FullName.Length+1);
                ZipArchiveEntry readmeEntry = archive.CreateEntryFromFile(file.FullName, relPath);
            }
        }
    }
}

zip-archive에서 폴더를 "생성"할 필요가 없습니다. CreateEntryFromFile의 두 번째 매개 변수 "entryName"은 상대 경로 여야하며 zip 파일의 압축을 풀 때 상대 경로의 디렉토리가 감지되고 생성됩니다.


.NET 3, 3.5 및 4.0에 내장 된 System.IO.Packaging 네임 스페이스에 ZipPackage 클래스가 있습니다.

http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx

다음은 사용 방법의 예입니다. http://www.codeproject.com/KB/files/ZipUnZipTool.aspx?display=Print


순수하게 C #으로 파일과 폴더를 압축 및 압축 해제하기위한 샘플 응용 프로그램이있는 MSDN 의 기사가 있습니다 . 나는 오랫동안 성공적으로 수업 중 일부를 사용해 왔습니다. 코드는 Microsoft Permissive License에 따라 배포됩니다.

편집 : 내가 시대에 조금 뒤처 졌다는 것을 지적한 Cheeso에게 감사드립니다. 내가 지적한 MSDN 예제는 실제로 DotNetZip을 사용 하고 있으며 요즘에는 정말 모든 기능을 갖추고 있습니다. 이전 버전에 대한 경험을 바탕으로 기꺼이 권장합니다.

SharpZipLib 은 또한 상당히 성숙한 라이브러리이며 사람들로부터 높은 평가를 받고 있으며 GPL 라이선스에 따라 사용할 수 있습니다. 압축 요구 사항과 각 라이선스 조건을 보는 방법에 따라 다릅니다.

풍부한


다음 코드는 Rebex의 타사 ZIP 구성 요소를 사용합니다 .

// add content of the local directory C:\Data\  
// to the root directory in the ZIP archive
// (ZIP archive C:\archive.zip doesn't have to exist) 
Rebex.IO.Compression.ZipArchive.Add(@"C:\archive.zip", @"C:\Data\*", "");

또는 아카이브를 여러 번 열고 닫을 필요없이 더 많은 폴더를 추가하려는 경우 :

using Rebex.IO.Compression;
...

// open the ZIP archive from an existing file 
ZipArchive zip = new ZipArchive(@"C:\archive.zip", ArchiveOpenMode.OpenOrCreate);

// add first folder
zip.Add(@"c:\first\folder\*","\first\folder");

// add second folder
zip.Add(@"c:\second\folder\*","\second\folder");

// close the archive 
zip.Close(ArchiveSaveAction.Auto);

여기에서 ZIP 구성 요소를 다운로드 할 수 있습니다 .

무료 LGPL 라이센스를 사용하는 SharpZipLib 은 일반적인 대안입니다.

면책 조항 : 저는 Rebex에서 일합니다


DotNetZip 사용 (nuget 패키지로 사용 가능) :

public void Zip(string source, string destination)
{
    using (ZipFile zip = new ZipFile
    {
        CompressionLevel = CompressionLevel.BestCompression
    })
    {
        var files = Directory.GetFiles(source, "*",
            SearchOption.AllDirectories).
            Where(f => Path.GetExtension(f).
                ToLowerInvariant() != ".zip").ToArray();

        foreach (var f in files)
        {
            zip.AddFile(f, GetCleanFolderName(source, f));
        }

        var destinationFilename = destination;

        if (Directory.Exists(destination) && !destination.EndsWith(".zip"))
        {
            destinationFilename += $"\\{new DirectoryInfo(source).Name}-{DateTime.Now:yyyy-MM-dd-HH-mm-ss-ffffff}.zip";
        }

        zip.Save(destinationFilename);
    }
}

private string GetCleanFolderName(string source, string filepath)
{
    if (string.IsNullOrWhiteSpace(filepath))
    {
        return string.Empty;
    }

    var result = filepath.Substring(source.Length);

    if (result.StartsWith("\\"))
    {
        result = result.Substring(1);
    }

    result = result.Substring(0, result.Length - new FileInfo(filepath).Name.Length);

    return result;
}

용법:

Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest");

또는

Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest\output.zip");

"Where should I copy ICSharpCode.SharpZipLib.dll to see that namespace in Visual Studio?"

프로젝트에서 참조로 dll 파일을 추가해야합니다. 솔루션 탐색기-> 참조 추가-> 찾아보기에서 참조를 마우스 오른쪽 단추로 클릭 한 다음 dll을 선택하십시오.

Finally you'll need to add it as a using statement in whatever files you want to use it in.


ComponentPro ZIP can help you achieve that task. The following code snippet compress files and dirs in a folder. You can use wilcard mask as well.

using ComponentPro.Compression;
using ComponentPro.IO;

...

// Create a new instance.
Zip zip = new Zip();
// Create a new zip file.
zip.Create("test.zip");

zip.Add(@"D:\Temp\Abc"); // Add entire D:\Temp\Abc folder to the archive.

// Add all files and subdirectories from 'c:\test' to the archive.
zip.AddFiles(@"c:\test");
// Add all files and subdirectories from 'c:\my folder' to the archive.
zip.AddFiles(@"c:\my folder", "");
// Add all files and subdirectories from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2", "22");
// Add all .dat files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2", "22", "*.dat");
// Or simply use this to add all .dat files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2\*.dat", "22");
// Add *.dat and *.exe files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2\*.dat;*.exe", "22");

TransferOptions opt = new TransferOptions();
// Donot add empty directories.
opt.CreateEmptyDirectories = false;
zip.AddFiles(@"c:\abc", "/", opt);

// Close the zip file.
zip.Close();

http://www.componentpro.com/doc/zip has more examples

참고URL : https://stackoverflow.com/questions/905654/zip-folder-in-c-sharp

반응형