Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
922 views
in Technique[技术] by (71.8m points)

compression - How do I ZIP a file in C#, using no 3rd-party APIs?

I'm pretty sure this is not a duplicate so bear with me for just a minute.

How can I programatically (C#) ZIP a file (in Windows) without using any third party libraries? I need a native windows call or something like that; I really dislike the idea of starting a process, but I will if I absolutely have to. A PInovke call would be much better.

Failing that, let me tell you what I'm really trying to accomplish: I need the ability to let a user download a collection of documents in a single request. Any ideas on how to accomplish this?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How can I programatically (C#) ZIP a file (in Windows) without using any third party libraries?

If using the 4.5+ Framework, there is now the ZipArchive and ZipFile classes.

using (ZipArchive zip = ZipFile.Open("test.zip", ZipArchiveMode.Create))
{
    zip.CreateEntryFromFile(@"c:something.txt", "data/path/something.txt");
}

You need to add references to:

  • System.IO.Compression
  • System.IO.Compression.FileSystem

For .NET Core targeting net46, you need to add dependencies for

  • System.IO.Compression
  • System.IO.Compression.ZipFile

Example project.json:

"dependencies": {
  "System.IO.Compression": "4.1.0",
  "System.IO.Compression.ZipFile": "4.0.1"
},

"frameworks": {
  "net46": {}
}

For .NET Core 2.0, just adding a simple using statement is all that is needed:

  • using System.IO.Compression;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...