如何在.NET中正确转义文档名称?

编程入门 行业动态 更新时间:2024-10-27 08:33:29
本文介绍了如何在.NET中正确转义文档名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我们在我们的网络服务器(人们上传它们)上存储一堆奇怪的文件名称,它们具有空格,&符号等各种字符。当我们生成链接到这些文档时,我们需要转义它们,以便服务器可以查找该文件以其原始名称在数据库中。但是,所有内置.NET转义函数都不能正常工作。

获取文档 Hello#There.docx

UrlEncode 将正确处理:

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

然而, UrlEncode 将不句柄您好..docx 正确:

HttpUtility.UrlEncode(Hello There.docx); 你好+ There.docx

+ 符号仅对URL参数有效,而不适用于文档名称。有趣的是,这实际上可以在Visual Studio测试Web服务器上工作,但不在IIS上。

UrlPathEncode 空格:

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

但是,它不会转义其他字符,如#字符:

HttpUtility.UrlPathEncode(Hello#there DOCX); Hello#There.docx

此链接无效,因为#被解释为一个URL哈希,从来没有甚至到达服务器。

是否有一个.NET实用程序方法来转义所有非文件名中的字母数字字符,还是我必须自己写?

解决方案

看看 Uri.EscapeDataString方法:

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

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.

Take the document Hello#There.docx:

UrlEncode will handle this correctly:

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

However, UrlEncode will not handle Hello There.docx correctly:

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

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.

The UrlPathEncode function works fine for spaces:

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

However, it will not escape other characters such as the # character:

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

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

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

解决方案

Have a look at the Uri.EscapeDataString Method:

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

更多推荐

如何在.NET中正确转义文档名称?

本文发布于:2023-10-23 22:26:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1522177.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   名称   文档   如何在   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!