Many applications integrate content with various additional resources. A Web browser, for example, displays a page that integrates HTML, image files, style sheets, and other types of content. Similarly, a word processor builds a document that combines text, style definitions, image files, and other elements. For the most part, applications use one of two approaches to organize the content: a flat-file organization where content is stored as separate files organized on disk, or binary container files where all the content is packaged in a single custom file. More and more, applications are tending towards the latter.
从Office2007开始Microsoft开始全面采用OPC格式,同时.NET3.5提供了Packaging来支持OPC的读取。
一个OPC可以理解为一个Package,Package内包含多个Part和一组Relation,我们暂且无视Relation,我们试着将两张图片打包已成一个sample.pkg
string part1 = @"C:/users/nonocast.DEV.000/desktop/part1.jpg";
string part2 = @"C:/users/nonocast.DEV.000/desktop/part2.jpg";
Uri part1Uri = PackUriHelper.CreatePartUri(new Uri(@"/part1.jpg", UriKind.Relative));
Uri part2Uri = PackUriHelper.CreatePartUri(new Uri(@"/part2.jpg", UriKind.Relative));
using (Package pkg = Package.Open("./sample.pkg")) {
PackagePart pkgPart1 = pkg.CreatePart(part1Uri, DefaultContentType, CompressionOption.Maximum);
using (FileStream fs1 = File.OpenRead(part1)) {
fs1.CopyTo(pkgPart1.GetStream());
}
PackagePart pkgPart2 = pkg.CreatePart(part2Uri, DefaultContentType, CompressionOption.Maximum);
using (FileStream fs2 = File.OpenRead(part2)) {
fs2.CopyTo(pkgPart2.GetStream());
}
}
...
private const string DefaultContentType = "application/octet";
运行了你会在exe同目录下得到sample.pkg,sample.pkg是一个标准的zip format,直接通过解压缩工具打开可以看到如下:

如果需要对一个目录打包,只需要逐一加入即可,
string targetFolder = @"e:\nuget\src\CommandLine";
using (Package pkg = Package.Open("./sample.pkg")) {
var files = PathResolver.ResolveSearchPattern(targetFolder, @"**\*.*", null);
foreach (var each in files) {
Uri partUri = UriUtility.CreatePartUri(each.TargetPath);
PackagePart pkgpart = pkg.CreatePart(partUri, DefaultContentType, CompressionOption.Maximum);
using (FileStream fs = File.OpenRead(each.SourcePath)) {
fs.CopyTo(pkgpart.GetStream());
}
}
}
PathResolver和UriUtility均取自Nuget代码,上述代码戳这里。
参考文章:






