- 郁悶了一天終於搞定這個問題了,出現這個問題時候文件其實內容還是可以打開的,就是出現以上的錯誤原因。經過最終分析確定了具體原因,是因為在Response下載文檔時候,最后需要結束
System.Web.HttpContext.Current.Response.End();否則默認為不完整下載狀態。反正我加上去后就不出現以上情況了。具體代碼如下:
/// <summary> /// 下載文件 /// </summary> public void LoadPaperTemplate(string mStrFileName) { FileStream fs = null; BinaryReader br = null; BinaryWriter brnew = null; try { //給內容賦值 string path = System.Web.HttpContext.Current.Server.MapPath("~/Template"); string mStrFileRoot = string.Format("{0}\\{1}", path, mStrFileName); if (File.Exists(mStrFileRoot)) { fs = new System.IO.FileStream(mStrFileRoot, System.IO.FileMode.Open); br = new BinaryReader((Stream)fs); byte[] bytes = br.ReadBytes((Int32)fs.Length); brnew = new BinaryWriter(fs); brnew.Write(bytes, 0, bytes.Length); System.Web.HttpContext.Current.Response.Clear(); System.Web.HttpContext.Current.Response.Buffer = true; System.Web.HttpContext.Current.Response.Charset = "GB2312"; System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(mStrFileRoot.Substring(mStrFileRoot.LastIndexOf('\\') + 1))); System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); System.Web.HttpContext.Current.Response.ContentType = "application/ms-word"; System.Web.HttpContext.Current.Response.BinaryWrite(bytes); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End(); } } catch (Exception) { //throw; } finally { br.Close(); brnew.Close(); fs.Close(); } }