你如何正确逃生.NET中的文件名?文件名、如何正确、NET

2023-09-03 06:33:33 作者:倾一座城,淡一场梦

我们保存了一堆我们的Web服务器上的怪异的文件名(人快点上传)有不同的字符,如空格,与符号等等。当我们生成链接到这些文件,我们需要逃避他们,让服务器可以查找该文件通过其数据库中的原始名称。然而,没有内置的.NET逃生功能将在所有情况下正常工作。

We store a bunch of weird document names on our web server (people upload them) that have various characters like spaces, ampersands, etc. When we generate links to these documents, we need to escape them so the server can look up the file by its raw name in the database. However, none of the built in .NET escape functions will work correctly in all cases.

取文件您好#There.docx

UrlEn code 将正确处理这个问题:

UrlEncode will handle this correctly:

HttpUtility.UrlEncode("Hello#There");
"Hello%23There"

不过, UrlEn code 将没有的手柄您好There.docx 正确的:

HttpUtility.UrlEncode("Hello There.docx");
"Hello+There.docx"

+ 符号只适用于URL参数,而不是文件名。有趣的是,这确实可以工作在Visual Studio测试Web服务器上而不是在IIS。

The + symbol is only valid for URL parameters, not document names. Interestingly enough, this actually works on the Visual Studio test web server but not on IIS.

UrlPathEn code 功能工作正常的空间:

The UrlPathEncode function works fine for spaces:

HttpUtility.UrlPathEncode("Hello There.docx");
"Hello%20There.docx"

不过,它不会逃避其他字符,如字符:

HttpUtility.UrlPathEncode("Hello#There.docx");
"Hello#There.docx"

这个链接是无效的,因为是PTED为URL散列甚至从来没有跨$ P $获取到服务器。

This link is invalid as the # is interpreted as a URL hash and never even gets to the server.

有一个.NET实用方法逃避文档名称的所有非字母数字字符,或者我会写我自己?

Is there a .NET utility method to escape all non-alphanumeric characters in a document name, or would I have to write my own?

推荐答案

有一个看的 Uri.EscapeDataString方法:

Uri.EscapeDataString("Hello There.docx")  // "Hello%20There.docx"

Uri.EscapeDataString("Hello#There.docx")  // "Hello%23There.docx"