你如何正确逃生.NET中的文件名? [英] How do you correctly escape a document name in .NET?

查看:141
本文介绍了你如何正确逃生.NET中的文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们保存了一堆我们的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"

这篇关于你如何正确逃生.NET中的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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