日期:2014-05-17  浏览次数:20479 次

ASP.NET下载的一个奇怪问题
代码如下...谢谢看下代码!下载的时候总是下载的不是写入txt的内容,而是这个页面的网页代码内容!txt在相关文件夹中正确写入并且有
C# code


 if (!Directory.Exists(Server.MapPath("UserTemp")))
            {
                Directory.CreateDirectory(Server.MapPath("UserTemp"));
            }
            string path = Path.Combine("UserTemp//", "白名单导出_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt");
            string str5 = base.Server.MapPath(path);

            if (File.Exists(str5))
            {
                File.Delete(str5);
            }
            //数据量大用另外一种方法
            FileInfo file = new FileInfo(str5);//用于获取文件信息
            StreamWriter textFile = null;
            textFile = file.CreateText();


            string sqlWhile = "SELECT WMobile FROM WMobile";
            DataTable tab = new DataTable();
            tab = DBCommonClass.DbAccessHelper.ExecuteDataTable(new DbCommandData(sqlWhile));
            string strWhile = string.Empty;
            for (int i = 0; i < tab.Rows.Count; i++)
            {
                string str = tab.Rows[i][0].ToString();
                strWhile += str + "\r\n";
            }

            textFile.Write(strWhile);
            textFile.Close();

///////////////////////////////////////////////////下面就是下载代码了
            //Response.Clear();//清空输出
            //Response.Charset = "GB2312";//设定编码
            //Response.ContentEncoding = System.Text.Encoding.UTF8;
            //Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(file.Name));
            //Response.AddHeader("Content-length", file.Length.ToString());
            //Response.ContentType = "application/octet-stream";
            ////ms-txt";
            //Response.WriteFile(file.FullName);
            //Response.End();
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(file.Name, Encoding.UTF8));
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.WriteFile(file.FullName);
            Response.Flush();
            HttpContext.Current.ApplicationInstance.CompleteRequest();







------解决方案--------------------
1,测试的时候每次都打开一个新的浏览器窗口
2,你可以
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(file.Name, Encoding.UTF8));

改成
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(file.Name, Encoding.UTF8) + ".txt");

看看是不是把扩展名也编码了

编码的时候只编码文件名,不要包括扩展名