今天测试文件下载程序中发现的文件名过长的问题

王朝c#·作者佚名  2006-12-17
窄屏简体版  字體: |||超大  

居然发现文件名编码后长度超过155就会不能正确显示和下载,最后只好找了这样一个折中的方法,截短了

下面是那里的代码

/// <summary>

/// 下载附件。

/// </summary>

/// <param name="fileName">文件名</param>

/// <param name="path">文件路径</param>

public static void DownLoadFileAttachment(string fileName , string path)

{

if (System.IO.File.Exists(path))

{

try

{

fileName = fileName.Trim();

for (int i = 0 ; i < System.IO.Path.InvalidPathChars.Length ; i ++)

{

fileName = fileName.Trim().Replace(System.IO.Path.InvalidPathChars[i].ToString() , string.Empty);

}

fileName = fileName.Replace(System.IO.Path.PathSeparator.ToString() , string.Empty);

int maxLength = 155;

int length = HttpUtility.UrlEncode(fileName).Length;

while (length > maxLength)

{

int index = fileName.LastIndexOf(".");

if (index > 0)

{

fileName = fileName.Substring(0 , index - 1) + fileName.Substring(index);

}

else

{

fileName = fileName.Substring(0 , fileName.Length - 1);

}

length = HttpUtility.UrlEncode(fileName).Length;

}

System.IO.FileInfo file = new System.IO.FileInfo(path);

HttpContext.Current.Response.Clear();

HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));

HttpContext.Current.Response.AppendHeader("Content-Length", file.Length.ToString());

HttpContext.Current.Response.ContentType = "application/octet-stream";

HttpContext.Current.Response.WriteFile(file.FullName);

HttpContext.Current.Response.End();

}

catch

{

}

}

else

{

HttpContext.Current.Response.Clear();

DisplayNoFileMessage();

HttpContext.Current.Response.End();

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航