日期:2014-05-17 浏览次数:20646 次
protected void btnTest_Click(object sender, EventArgs e) { DownLoadFile("~/template.txt"); } /// <summary> /// 下载文件 /// </summary> /// <param name="fileName"></param> protected void DownLoadFile(string fileName) { try { string FullFileName = Server.MapPath(fileName); //FileName--要下载的文件名 FileInfo DownloadFile = new FileInfo(FullFileName); if (DownloadFile.Exists) { Response.Clear(); Response.ClearHeaders(); Response.Buffer = false; Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + ToHexString(DownloadFile.Name)); Response.AppendHeader("Content-Length", DownloadFile.Length.ToString()); Response.WriteFile(DownloadFile.FullName); Response.Flush(); Response.End(); } } catch { } } /// <summary> /// 为字符串中的非英文字符编码 /// </summary> /// <param name="s"></param> /// <returns></returns> public string ToHexString(string s) { char[] chars = s.ToCharArray(); StringBuilder builder = new StringBuilder(); for (int index = 0; index < chars.Length; index++) { bool needToEncode = NeedToEncode(chars[index]); if (needToEncode) { string encodedString = ToHexString(chars[index]); builder.Append(encodedString); } else { builder.Append(chars[index]); } } return builder.ToString(); } /// <summary> ///指定 一个字符是否应该被编码 /// </summary> /// <param name="chr"></param> /// <returns></returns> private bool NeedToEncode(char chr) { string reservedChars = "$-_.+!*'(),@=&"; if (chr > 127) return true; if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0) return false; return true; } /// <summary> /// 为非英文字符串编码 /// </summary> /// <param name="chr"></param> /// <returns></returns> private string ToHexString(char chr) { UTF8Encoding utf8 = new UTF8Encoding(); byte[] encodedBytes = utf8.GetBytes(chr.ToString()); StringBuilder builder = new StringBuilder(); for (int index = 0; index < encodedBytes.Length; index++) { builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16)); } return builder.ToString(); }