이 단계별 자습서에서는 C#에서 메모리에 ZIP 파일을 만드는 방법을 배웁니다. 메모리에 ZIP 아카이브를 만들려면 다음과 같은 간단한 단계를 실행해야 합니다.
C#의 메모리에 ZIP 파일을 만드는 단계
- 솔루션에 Aspose.ZIP for .NET NuGet 패키지 참조 추가
- Program.cs 코드 파일에 Aspose.Zip 문을 사용하여 추가
- License.SetLicense 메서드를 사용하여 Aspose.ZIP API에 대한 라이선스 적용
- 디스크에 있는 폴더에서 단일 또는 모든 파일을 가져오고 해당 경로를 문자열 배열에 저장합니다.
- 메모리에 Archive Class의 객체 생성
- 각 파일에 대해 ZIP 아카이브에 ArchiveEntry 노드를 만듭니다.
- ZIP 아카이브 인스턴스를 MemoryStream에 저장 또는 복사
다음 C# 코드 예제는 .NET 애플리케이션에서 디스크의 폴더에 있는 모든 파일을 ZIP file format로 압축한 다음 메모리 스트림 개체에 ZIP 파일을 저장하는 데 사용할 수 있습니다.
C#의 메모리에 ZIP 파일을 만드는 코드
using System.IO; | |
// Following namespace is required to Create ZIP File in Memory | |
using Aspose.Zip; | |
namespace CreateZipFileInMemory | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
License AsposeZipLicense = new License(); | |
// Load license from file system into memory stream | |
using (MemoryStream stream = new MemoryStream(File.ReadAllBytes("path to license.lic"))) | |
{ | |
// Set license prior to creating ZIP file in memory | |
AsposeZipLicense.SetLicense(stream); | |
} | |
#region C# code to create ZIP archive in memory | |
// Create MemoryStream instance | |
using (MemoryStream zipFileInMemory = new MemoryStream()) | |
{ | |
// Create empty Archive object for ZIP file | |
using (Aspose.Zip.Archive zipArchive = new Aspose.Zip.Archive()) | |
{ | |
// Get all files from a Folder and store their paths in string Array | |
string[] filesArray = Directory.GetFiles("ZIP all Files\\", "*.*", SearchOption.TopDirectoryOnly); | |
// Loop through the Array and create an ArchiveEntry against each file within the ZIP Archive | |
foreach (string fileDiskPath in filesArray) | |
{ | |
string[] folders = fileDiskPath.Split(new char[] { '\\' }); | |
string fileName = folders[folders.Length - 1]; | |
zipArchive.CreateEntry(fileName, fileDiskPath); | |
} | |
// Call Save method to create ZIP Archive in memory | |
zipArchive.Save(zipFileInMemory); | |
} | |
} | |
#endregion | |
} | |
} | |
} |
따라서 이 C# 메모리 콘솔 응용 프로그램에서 zip 파일 만들기는 기본적으로 폴더를 ZIP 형식으로 변환하고 폴더의 전체 내용을 압축 형식으로 메모리에 쓰는 데 도움이 됩니다. 그런 다음 MemoryStream C#에서 ZIP 파일을 다시 만들고 디스크에 저장할 수 있습니다. 아카이브가 파일 시스템에 다시 생성되면 C#을 사용하여 ZIP 파일 추출 코드를 작성할 수 있습니다.