通过System.IO.Packaging实现打包和解包
微软提供了System.IO.Packaging类库用于打包和解包,这样文件的打包和解包就很方便了,代码如下:
1 class Program {
2 static string sourceFolder = @"d:\source";
3 static string targetFolder = @"d:\target";
4 static string pkgFile = @"d:\package.pkg";
5
6 static void Main(string[] args) {
7 CreatePackage();
8
9 //ExtractPackage();
10
11 Console.WriteLine("press any key to exits.");
12 Console.ReadLine();
13 }
14
15 static void CreatePackage() {
16 using (Package pkg = Package.Open(pkgFile, FileMode.Create)) {
17 var files = PathResolver.ResolveSearchPattern(sourceFolder, @"**\*.*", null);
18 foreach (var each in files) {
19 Uri partUri = UriUtility.CreatePartUri(each.TargetPath);
20 PackagePart pkgpart = pkg.CreatePart(partUri, MediaTypeNames.Application.Octet, CompressionOption.Maximum);
21 using (FileStream fs = File.OpenRead(each.SourcePath)) {
22 fs.CopyTo(pkgpart.GetStream());
23 }
24 }
25 }
26 }
27
28 static void ExtractPackage() {
29 if (Directory.Exists(targetFolder)) {
30 Directory.Delete(targetFolder, true);
31 }
32
33 using (Package pkg = Package.Open(pkgFile, FileMode.Open)) {
34 foreach (var each in pkg.GetParts()) {
35 string relativePath = Uri.UnescapeDataString(each.Uri.ToString().TrimStart('/'));
36 string absolutePath = Path.Combine(targetFolder, relativePath);
37 Directory.CreateDirectory(Path.GetDirectoryName(absolutePath));
38
39 using (FileStream fs = new FileStream(absolutePath, FileMode.Create)) {
40 each.GetStream().CopyTo(fs);
41 }
42 }
43 }
44 }
45 }
说明:
1. sourceFolder为需要打包的目录,targetFolder为解包的目录,pkgFile为打包的文件名。
2. 37行的Directory.CreateDirectory用于创建解包的根目录和下面可能有的子目录。
3. 代码中用到的PathResolver和UriUtility均取自Nuget代码。
4. 代码下载