【问题标题】:how to save file with illegal name如何保存具有非法名称的文件
【发布时间】:2012-04-13 07:06:13
【问题描述】:

这是我创建文件的方式:

System.IO.File.Create(Server.MapPath("..") + name + ".html");

但有时名称包含瑞典字母表中的非法字符,例如 å。如何拯救他们?可以直接使用,但是使用代码时会出错。

【问题讨论】:

标签: c#


【解决方案1】:

如果路径是用户控制的并且可能包含无效的文件系统字符,那么您需要要求用户更改名称或以一种确定的方式规范化坏字符。一种方法是用下划线替换所有无效字符。

public static string NormalizeFileName(string input) {
  var invalid = Path.GetInvalidPathChars();
  var builder = new System.Text.StringBuilder();
  foreach(char c in input) {
    if (invalid.Contains(c)) {
      builder.Append('_');
    } else {
      builder.Append(c);
    }
  }
  return builder.ToString();
}

然后您可以按如下方式使用此功能

var originalName = Server.MapPath("..") + name + ".html";
var normalizedName = NormalizeFileName(originalName);
System.IO.File.Create(normalizedName);

编辑

正如一些人指出的,最佳做法是在此处使用Path.Combine 来组合目录和文件名。

var originalName = Path.Combine(Server.MapPath(".."), name + ".html");

【讨论】:

  • 如果他使用Path.Combine(Server.MapPath(".."), Path.ChangeExtension(NormalizeFileName(name), ".html")),它可能会解决一些极端情况。
【解决方案2】:
System.IO.File.Create(Server.MapPath("..") + "\\" + name + ".html"); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 2017-08-12
    相关资源
    最近更新 更多