2013-07-17 76 views
0

我使用system.io.packaging.package創建包含某些文件的包。 目的是創建一個導入/導出功能。ASP.Net:system.io.packaging包「文件包含損壞的數據」

我創建包這樣的:

 // 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應用程序中工作。

回答

0

最後我發現我的錯誤:

當我回到這個生成的包我回到了包,但整個網頁了。

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(); 

它的工作原理:)

相關問題