我正在使用 system.io.packaging.package 创建一个包含一些文件的包。目的是创建导入/导出功能。
我这样创建包:
// Create the compressed file.
using (FileStream outFile = File.Create(this.packageName))
{
using (Package Compress = Package.Open(outFile, FileMode.Create))
{
foreach (string file in Directory.GetFiles(Path.GetDirectoryName(this.packageName)))
{
FileInfo fi = new FileInfo(file);
// Prevent compressing hidden and already compressed files.
if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fi.Extension != ".gz")
{
PackagePart packagePartDocument;
if (fi.Extension == ".xml")
{
packagePartDocument = Compress.CreatePart(PackUriHelper.CreatePartUri(new Uri(@"/" + Path.GetFileName(file), UriKind.Relative)), System.Net.Mime.MediaTypeNames.Text.Xml);
}
else
{
packagePartDocument = Compress.CreatePart(PackUriHelper.CreatePartUri(new Uri(@"/" + Path.GetFileName(file), UriKind.Relative)), System.Net.Mime.MediaTypeNames.Text.Plain);
}
using (FileStream inFile = fi.OpenRead())
{
inFile.CopyTo(packagePartDocument.GetStream());
}
Compress.CreateRelationship(packagePartDocument.Uri, TargetMode.Internal, fi.FullName);
}
}
}
}
我是这样读的:
using (Package zip = Package.Open(PackageStream, FileMode.Open, FileAccess.Read, FileShare.None))
{
Directory.CreateDirectory(Path.Combine(App.Configuration.TempDirectory, this.packageName.Split('.')[0]));
foreach (PackagePart file in zip.GetParts())
{
string fileName = Path.Combine(App.Configuration.TempDirectory, this.packageName.Split('.')[0], file.Uri.ToString().TrimStart('/'));
using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
{
file.GetStream().CopyTo(fileStream);
}
}
}
包尝试打开文件时出现我的问题
Package zip = Package.Open(PackageStream, FileMode.Open, FileAccess.Read, FileShare.None)
我有一个错误“文件包含损坏的数据”
试了好多遍还是没看懂。。。
编辑:相同的代码正在使用控制台应用程序,但不适用于 Web 应用程序。