2012-02-03 4 views
1

私はこのコードで*.ashx(ハンドラ) を持っている:IonicZip/DotNetZip閉じたファイルにアクセスできません。 context.Response.OutputStream

public void ProcessRequest (HttpContext context) { 
    context.Response.ContentType = "application/zip"; 
    context.Response.AddHeader("Content-Disposition", "attachment; filename=catalog" + DateTime.Now.ToString("yyyy-MM-dd") + ".zip"); 

    // magic happends here to get a DataTable called 'dt' 

    using (ZipFile zip = new ZipFile(Encoding.UTF8)) 
    { 
     foreach (DataRow dr in dt.Rows) 
     { 
      string barCode = "C:/tmp/bc/" + dr["ProductCode"] + ".gif"; 

      if (File.Exists(barCode)) 
      { 
       if (!zip.EntryFileNames.Contains("bc" + dr["ProductCode"] + ".gif")) 
       { 
        try 
        { 
         // this option does not work 
         using (StreamReader sr = new StreamReader(barCode)) 
         { 
          if (sr.BaseStream.CanRead) 
           zip.AddEntry("bc" + dr["ProductCode"] + ".gif", sr.BaseStream); 
         } 
         // but the next line does work... WHY? 
         zip.AddEntry("bc" + dr["ProductCode"] + ".gif", File.ReadAllBytes(barCode)); 
        } 
        catch (Exception ex) 
        { 
         // never hits the catch 
         context.Response.Write(ex.Message); 
        } 
       } 
      } 
     } 
     zip.Save(context.Response.OutputStream); // here is the exception if I use the first option 
    } 
} 

私はhttp://dotnetzip.codeplex.com/ の最新バージョンを使用File.ReadAllBytesが仕事とStreamReaderないクラッシュしない理由を誰かが私に説明することができますOutputStreamに保存すると 例外メッセージはです。クローズファイルにアクセスできない

答えて

2

ストリームをusingステートメントでラップするのが問題です。 usingステートメントの終わりに、ストリームが配置されます。

zip.saveに電話すると、ライブラリは閉じられたストリームにアクセスしようとします。 File.ReadAllBytesはデータを直接渡すので失敗しません。

public void ProcessRequest (HttpContext context) { 
context.Response.ContentType = "application/zip"; 
context.Response.AddHeader("Content-Disposition", "attachment; filename=catalog" + DateTime.Now.ToString("yyyy-MM-dd") + ".zip"); 

    using (ZipFile zip = new ZipFile(Encoding.UTF8)) 
    { 
     foreach (DataRow dr in dt.Rows) 
     { 
      string barCode = "C:/tmp/bc/" + dr["ProductCode"] + ".gif"; 

      if (File.Exists(barCode)) 
      { 
       if (!zip.EntryFileNames.Contains("bc" + dr["ProductCode"] + ".gif")) 
       { 
        try 
        { 
         // The file stream is opened here 
         using (StreamReader sr = new StreamReader(barCode)) 
         { 
          if (sr.BaseStream.CanRead) 
           zip.AddEntry("bc" + dr["ProductCode"] + ".gif", sr.BaseStream); 
         } 
         // The file stream is closed here 
        } 
        catch (Exception ex) 
        { 
         // never hits the catch 
         context.Response.Write(ex.Message); 
        } 
       } 
      } 
     } 

     // The closed file streams are accessed here 
     zip.Save(context.Response.OutputStream); 
    } 
} 
関連する問題