2012-03-05 20 views
0

我正在使用webmethod下載.zip文件,但文件未下載。我的代碼沒有錯誤運行良好,代碼如下:
未在webmethod中下載的文件

[WebMethod] 
    public static void DownloadExtension(string ExtensionPath) 
    { 
     string filepath = HttpContext.Current.Server.MapPath(ExtensionPath); 
     FileInfo file = new FileInfo(filepath); 
     if (file.Exists) 
     { 
      HttpContext.Current.Response.ClearContent(); 
      HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 
      HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString()); 
      HttpContext.Current.Response.ContentType = ReturnExtension(file.Extension.ToLower()); 
      HttpContext.Current.Response.TransmitFile(file.FullName); 
      HttpContext.Current.Response.End(); 
     } 
    } 

    private static string ReturnExtension(string fileExtension) 
    { 
     switch (fileExtension) 
     {    
      case ".zip": 
       return "application/zip"; 
      default: 
       return "application/octet-stream"; 
     } 
    } 


我使用VS2008 任何解決方案謝謝。

回答

1

ü可以試試這個method..it工作得很好,我...希望它可以幫助你..

  protected void Page_Load(object sender, EventArgs e) 
{ 
    StartZip(Server.MapPath("directory name"), "filename");  
} 

protected void StartZip(string strPath, string strFileName) 
{ 
    MemoryStream ms = null; 
    Response.ContentType = "application/octet-stream"; 
    strFileName = HttpUtility.UrlEncode(strFileName).Replace('+', ' '); 
    Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName + ".zip"); 
    ms = new MemoryStream(); 
    zos = new ZipOutputStream(ms); 
    strBaseDir = strPath + "\\"; 
    addZipEntry(strBaseDir); 
    zos.Finish(); 
    zos.Close(); 
    Response.Clear(); 
    Response.BinaryWrite(ms.ToArray()); 
    Response.End(); 
} 

protected void addZipEntry(string PathStr) 
{ 
    DirectoryInfo di = new DirectoryInfo(PathStr); 
    foreach (DirectoryInfo item in di.GetDirectories()) 
    { 
     addZipEntry(item.FullName); 
    } 
    foreach (FileInfo item in di.GetFiles()) 
    { 
     FileStream fs = File.OpenRead(item.FullName); 
     byte[] buffer = new byte[fs.Length]; 
     fs.Read(buffer, 0, buffer.Length); 
     string strEntryName = item.FullName.Replace(strBaseDir, ""); 
     ZipEntry entry = new ZipEntry(strEntryName); 
     zos.PutNextEntry(entry); 
     zos.Write(buffer, 0, buffer.Length); 
     fs.Close(); 
    } 
} 
1

試圖通過一個ashx的處理程序文件下載該文件。