我正在使用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尝试打开文件时
Package zip = Package.Open(PackageStream, FileMode.Open, FileAccess.Read, FileShare.None)
我有一个错误"文件包含损坏的数据"
我一遍又一遍地做了很多测试,但我不明白。。。
编辑:同样的代码也适用于控制台应用程序,但不适用于web应用程序。
最后我发现了我的错误:
当我返回这个生成的包时,我会返回包,但也会返回整个网页。
Response.AddHeader("content-disposition", "attachment; filename=" + export.PackageName);
Response.ContentType = "application/octet-stream";
Response.WriteFile(export.PackageFullName);
所以我用纠正了它
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + export.PackageName);
Response.ContentType = "application/octet-stream";
Response.WriteFile(export.PackageFullName);
Response.Flush();
Response.End();
它的工作原理是:)