文件下载程序中文件名过长的问题

分类: C#   出处:iocblog整理  更新时间:2008-12-08   添加到收藏  


  今天测试文件下载程序中发现的文件名过长的问题 ,居然发现文件名编码后长度超过155就会不能正确显示和下载,最后只好找了这样一个折中的方法,截短了
  下面是那里的代码
  /// <summary>
  /// 下载附件。
  /// </summary>
  /// <param name="filename">文件名</param>
  /// <param name="path">文件路径</param>(来源 www.iocblog.net)
  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();
  }
  }
  (来源 www.iocblog.net)



文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。