使用C#URL编码URL

2023-09-02 10:17:10 作者:誰與我狂

我有我的朋友开发的应用程序。它发出了一个POST请求VB论坛软件,并记录有人在(与出设置cookie或任何东西)。

I have an application which I've developed for a friend. It sends a POST request to the VB forum software and logs someone in (with out setting cookies or anything).

一旦创建,创建其本地计算机上的路径变量的用户登录。

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

C: tempfolder 日用户名

c:tempfolderdateusername

现在的问题是,一些用户名扔非法字符异常。例如,如果我的用户名是金管局|菲尼克斯将抛出异常。

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连接code是不是我想要的。这里就是我想要做的:

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.

推荐答案

编辑:请注意,这个答案现在已经过时了。请参见下面 drweb86的回答,共创美好修复

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

URL编码会做你的建议在这里什么。在C#中,您只需使用 HttpUtility ,如提及。

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

您也可以正则表达式非法字符,然后替换,但是这得要复杂得多,因为你必须有某种形式的状态机(开关...情况下,例如),以取代正确的字符。由于 UrlEn code 这是否达阵,这是相当容易的。

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的对比窗,也有一些字符是可以接受在Linux中是无法在Windows,但我不会担心,因为该文件夹的名称可以通过解码URL字符串,用 UrlDe code ,这样你就可以往返的变化。

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.