在.net中是否有内置方法来编码文件路径,就像编码url一样?例如,如果我在文件名中有非法字符,比如"what:whatever",我希望它编码":",所以它仍然存在,只是进行编码,以便系统接受它.我想做点什么Path.Encode(fileName)
有什么像这样的吗?
这就是我正在做的事情.我在wikipedia.org上搜索我在www.wikipediamaze.com上创建的游戏.当我进行屏幕抓取时,我将结果缓存到我的app_data文件夹中的文件中,该文件与我所在的维基百科网站的当前主题的名称相匹配.例如,如果我在这个位置:
http://www.wikipedia.org/wiki/Kevin_Bacon
然后我刮掉那个页面,解析它,清理它等等,然后缓存在磁盘上以便以后更快地退出.它被存储在该位置/App_Data/Kevin_Bacon (no file extension).这非常有用,除非我在一个页面上
http://www.wikipedia.org/wiki/Wikipedia:About
尝试创建文件/App_Data/Wikipedia:About显然不起作用,因为':'字符在文件名中是非法的.
UPDATE
这对我很有用:
public static string EncodeAsFileName(this string fileName)
{
return Regex.Replace(fileName, "[" + Regex.Escape(
new string(Path.GetInvalidFileNameChars())) + "]", " ");
}
Run Code Online (Sandbox Code Playgroud)
是无效字符:\ /:?"<> |
您只需要使用GetInvalidFileNameChars函数:(http://msdn.microsoft.com/library/system.io.path.getinvalidfilenamechars.aspx)
string sanitizedString = Regex.Replace("Wikipedia:About", "[" + Regex.Escape(new string(Path.GetInvalidFileNameChars())) + "]", "_");
Run Code Online (Sandbox Code Playgroud)
所有无效字符都将替换为_(下划线).