且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将url转换为有效的文件名,然后返回url

更新时间:2023-02-23 18:50:58

首先值得指出的是."在文件名中完全合法,但是"/"不是合法的,因此尽管您引用的示例不需要翻译,但"www.ibm.com/path1/file1.jpg"将是必需的.

Firstly it's worth pointing out that "." is perfectly legal in file names, but "/" isn't, so while the example you quote doesn't need translating, "www.ibm.com/path1/file1.jpg" would.

在这里,简单的string.Replace是***的解决方案-假设您可以找到一个在文件名中合法但在url中非法的字符.

A simple string.Replace would be the best solution here - assuming you can find a character that's legal in a file name but illegal in a url.

假设非法的URL字符是§"(在URL中可能是合法的),那么您将得到:

Assuming that the illegal URL character is "§" (which may be legal in a URL), then you've got:

string.Replace("/", "§");

转换为文件名,然后:

string.Replace("§", "/");

翻译回来.

有关URL编码的页面定义了哪些有效,无效和URL的字符不安全(有效,但具有特殊含义). ISO-Latin设置为80-FF十六进制(十进制为128-255)的上半部分"中的字符是非法的,但在文件名中可能没问题.

This page on URL Encoding defines what are valid, invalid and unsafe (valid but with special meaning) characters for URLS. Characters in the "top half" of the ISO-Latin set 80-FF hex (128-255 decimal.) are not legal but might be OK in file names.

您将需要对无效文件名字符集中的URL中的每个字符执行此操作.您可以使用 GetInvalidFileNameChars 来获取.

You will need to do this for each character in the URL that is in the set of invalid file name characters. You can get this using GetInvalidFileNameChars.

更新

假设您找不到合适的字符对,那么另一种解决方案是使用查找表.一列保存URL,另一列保存URL.只要生成的名称是唯一的(GUID即可),您就可以进行两种查找以从一个查找到另一个.

Assuming that you can't find suitable character pairs, then another solution would be to use a lookup table. One column holds the URL the other the generated filename. As long as the generated name is unique (a GUID would do), you can do a two way lookup to get from one to the other.