使用 C# 进行 URL 编码 [英] URL Encoding using C#

查看:77
本文介绍了使用 C# 进行 URL 编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,它向 VB 论坛软件发送 POST 请求并让某人登录(不设置 cookie 或任何东西).

I have an application which sends a POST request to the VB forum software and logs someone in (without setting cookies or anything).

一旦用户登录,我就会创建一个变量,在他们的本地机器上创建一个路径.

Once the user is logged in I create a variable that creates a path on their local machine.

c: empfolderdate用户名

c: empfolderdateusername

问题是一些用户名抛出非法字符"异常.例如,如果我的用户名是 mas|fenix 它会抛出异常..

The problem is that some usernames are throwing "Illegal chars" exception. For example if my username was mas|fenix it would throw an exception..

Path.Combine( _      
  Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), _
  DateTime.Now.ToString("ddMMyyhhmm") + "-" + form1.username)

我不想从字符串中删除它,但是通过 FTP 在服务器上创建了一个带有用户名的文件夹.这就引出了我的第二个问题.如果我在服务器上创建一个文件夹,我可以保留非法字符"吗?我只是问这个,因为服务器是基于Linux的,我不确定Linux是否接受.

I don't want to remove it from the string, but a folder with their username is created through FTP on a server. And this leads to my second question. If I am creating a folder on the server can I leave the "illegal chars" in? I only ask this because the server is Linux based, and I am not sure if Linux accepts it or not.

似乎 URL 编码不是我想要的......这是我想要做的:

old username = mas|fenix
new username = mas%xxfenix

其中 %xx 是 ASCII 值或任何其他可以轻松识别字符的值.

Where %xx is the ASCII value or any other value that would easily identify the character.

推荐答案

请注意,此答案现已过时.请参阅Siarhei Kuchuk 下面的回答以获得更好的修复

Note that this answer is now out of date. See Siarhei Kuchuk's answer below for a better fix

UrlEncoding 将按照您在此处的建议进行操作.使用 C#,您只需使用 HttpUtility,如前所述.

UrlEncoding will do what you are suggesting here. With C#, you simply use HttpUtility, as mentioned.

您也可以对非法字符进行正则表达式然后替换,但这会变得更加复杂,因为您必须使用某种形式的状态机(例如 switch ... case)来替换正确的字符.由于 UrlEncode 是预先完成的,所以相当容易.

You can also Regex the illegal characters and then replace, but this gets far more complex, as you will have to have some form of state machine (switch ... case, for example) to replace with the correct characters. Since UrlEncode does this up front, it is rather easy.

对于Linux和windows,有一些在Linux中可以接受的字符在Windows中是可以接受的,但我不会担心,因为可以通过使用UrlDecode解码Url字符串来返回文件夹名称,因此您可以往返更改.

As for Linux versus windows, there are some characters that are acceptable in Linux that are not in Windows, but I would not worry about that, as the folder name can be returned by decoding the Url string, using UrlDecode, so you can round trip the changes.

这篇关于使用 C# 进行 URL 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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