代码改变世界

Asp.net 文件下载,中文文件名出现乱码

2012-04-20 13:11  suzh  阅读(910)  评论(0编辑  收藏  举报

最近在Asp.net项目中遇到一个问题,实现文件下载时,英文文件名的文件下载时,文件名显示正常,但是如果文件名为中文则显示乱码。

 

在网上google了一下,找到这编文章:解决用ASP.NET下载文件时,文件名为乱码的问题

string encodefileName= System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8); //通过使用HttpUtility.UrlEncode()来对原始文件名进行编码,以解决文件名乱码
Response.AppendHeader("content-disposition", "attachment;filename=" + encodefileName);//附件下载

但是以上这个方案,存在一个问题:就是如果文件名中有空格则空格变成了“+” 号,其他特殊字符尚未测试,有可能还存在其他问题。

 

再次使用google,终于找到老外的一编文章:Display a non-US-ASCII filename in File Download dialog box

他使用如下code解决问题:

string encodefileName=ToHexString(fileName);       //使用自定义的ToHexString()方法,编码原始文件名

Response.AppendHeader("content-disposition", "attachment;filename=" + encodefileName);

        /// <summary>
        /// Encodes non-US-ASCII characters in a string.
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static 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>
        /// Determines if the character needs to be encoded.
        /// </summary>
        /// <param name="chr"></param>
        /// <returns></returns>
        private static bool NeedToEncode(char chr)
        {
            string reservedChars = "$-_.+!*'(),@=&";

            if (chr > 127)
                return true;
            if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
                return false;

            return true;
        }

        /// <summary>
        /// Encodes a non-US-ASCII character.
        /// </summary>
        /// <param name="chr"></param>
        /// <returns></returns>
        private static 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();
        }

转自:http://www.cnblogs.com/shukunwang/archive/2010/02/04/1663885.html