2013-12-11 1 views
5

.NET Framework 4.5는 클래스를 통해 ZIP 파일에 대한 지원을 System.IO.Compression에 추가했습니다.C# .NET 4.5를 사용하여 ZIP 파일을 파일로 추출하지 않고 메모리로 읽어 오는 방법은 무엇입니까?

내가 루트에 sample.xml 파일을 가지고있는 .ZIP 아카이브를 가지고 있다고 가정 해 봅시다. 이 파일을 아카이브에서 메모리 스트림으로 직접 읽은 다음 사용자 지정 .NET 개체로 deserialize하려고합니다. 이 작업을 수행하는 가장 좋은 방법은 무엇입니까?

답변

10

ZipArchiveXmlSerializer.Deserialize() 매뉴얼 페이지에서 수정되었습니다.

ZipArchiveEntry 클래스에는 파일에 스트림을 반환하는 Open() 메서드가 있습니다. as documented on MSDN, 당신은 ZipFile 클래스를 사용하기 위해 .NET 어셈블리 System.IO.Compression.FileSystem에 대한 참조를 추가해야

string zipPath = @"c:\example\start.zip"; 

using (ZipArchive archive = ZipFile.OpenRead(zipPath)) 
{ 
    var sample = archive.GetEntry("sample.xml"); 
    if (sample != null) 
    { 
     using (var zipEntryStream = sample.Open()) 
     {    
      XmlSerializer serializer = new XmlSerializer(typeof(SampleClass)); 

      SampleClass deserialized = 
       (SampleClass)serializer.Deserialize(zipEntryStream); 
     } 
    } 
} 

참고.

+0

참고 ZipFile 클래스를 가져 오려면 System.IO.Compression.FileSystem 어셈블리에 대한 참조를 추가해야합니다. – sammy34

+1

@sammy thanks, updated. – CodeCaster