编码文件路径 [英] Encoding file paths

查看:133
本文介绍了编码文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在相同的方式将连接codeA URL编码文件路径内置方法在.net中?举例来说,如果我有非法字符的文件名,如什么:什么我想它连接code中的:所以它仍然存在,只是连接codeD,以便系统将接受它。我想要做这样的事情 Path.En code(文件名)

这样的事了吗?

下面是我在做什么。我刮wikipedia.org的游戏,我在 www.wikipediamaze.com 创建。当我做的屏幕抓取,我缓存所生成的文件在我的相匹配的维基百科网站,我对目前的主题名称App_Data文件夹。举例来说,如果我在的位置:

http://www.wikipedia.org/wiki/Kevin_Bacon

然后,我刮了网页,后来解析它,擦干净等,然后在磁盘缓存更快retireval。它得到的存储在该位置 / App_Data文件/ Kevin_Bacon(没有文件扩展名)。这个伟大的工程,除非我很喜欢

在页面上

http://www.wikipedia.org/wiki/Wikipedia:About

试图创建一个文件,在 / App_Data文件/维基百科:关于显然,因为不工作:字符是在文件名非法

更新

这对我的伟大工程:

 公共静态字符串连接codeAsFileName(此字符串文件名)
    {
        返回Regex.Replace(文件名,[+ Regex.Escape(
                新的字符串(Path.GetInvalidFileNameChars()))+],);
    }
 

解决方案

是无效字符:\ /:? <> |

您只需要使用GetInvalidFileNameChars功能: (<一href="http://msdn.microsoft.com/library/system.io.path.getinvalidfilenamechars.aspx">http://msdn.microsoft.com/library/system.io.path.getinvalidfilenamechars.aspx)

 字符串sanitizedString = Regex.Replace(百科:关于,[+ Regex.Escape(新的字符串(Path.GetInvalidFileNameChars()))+],_ );
 

所有无效的字符将被下划线(_)代替。

Is there a built in method in .net for encoding file paths in the same way you would encode a url? For instance, if I have illegal characters in a file name, like "whatever:whatever" I would like it to encode the ":" so it's still there, just encoded so that the system will accept it. I'd like to do something like Path.Encode(fileName)

Anything like this out there?

Here's what I'm doing. I'm scraping wikipedia.org for a game I've created at www.wikipediamaze.com. When I do the screen scraping, I cache the results in a file in my app_data folder that matches the name of the current topic of the wikipedia site that I'm on. For instance, if I'm at the location:

http://www.wikipedia.org/wiki/Kevin_Bacon

Then I scrape that page, parse it, clean it, etc., and then cache on disk for faster retireval later. It get's stored at the location /App_Data/Kevin_Bacon (no file extension). This works great unless I'm on a page like

http://www.wikipedia.org/wiki/Wikipedia:About

trying to create a file at /App_Data/Wikipedia:About obviously doesn't work since the ':' character is illegal in a file name.

UPDATE

This works great for me:

    public static string EncodeAsFileName(this string fileName)
    {
        return Regex.Replace(fileName, "[" + Regex.Escape(                             
                new string(Path.GetInvalidFileNameChars())) + "]", " ");
    }

解决方案

Are invalid characters: \ / : ? "< > |

You just need to use GetInvalidFileNameChars function: (http://msdn.microsoft.com/library/system.io.path.getinvalidfilenamechars.aspx)

string sanitizedString = Regex.Replace("Wikipedia:About", "[" + Regex.Escape(new string(Path.GetInvalidFileNameChars())) + "]", "_");

All invalid characters will be replaced by _ (underscore).

这篇关于编码文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆