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

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

c: \用户tempfolder枣\

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

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

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

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

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

其中%xx是ASCII值或任何其他容易识别字符的值。


当前回答

对于。net核心用户,使用这个

Microsoft.AspNetCore.Http.Extensions.UriHelper.Encode(Uri uri)

其他回答

如果你看不见系统。Web,更改项目设置。目标框架应该是。NET Framework 4“代替”。NET Framework 4客户端配置文件

更好的方法是使用

Uri。EscapeUriString

不引用。net 4的完整配置文件。

(更新)

根据OP的要求,推荐的API应该是

Uri。EscapeDataString

(谢谢@ykadaru)

对于。net核心用户,使用这个

Microsoft.AspNetCore.Http.Extensions.UriHelper.Encode(Uri uri)

UrlEncode的. net实现不符合RFC 3986。

Some characters are not encoded but should be. The !()* characters are listed in the RFC's section 2.2 as a reserved characters that must be encoded yet .NET fails to encode these characters. Some characters are encoded but should not be. The .-_ characters are not listed in the RFC's section 2.2 as a reserved character that should not be encoded yet .NET erroneously encodes these characters. The RFC specifies that to be consistent, implementations should use upper-case HEXDIG, where .NET produces lower-case HEXDIG.

您应该只对用户名或URL中可能无效的其他部分进行编码。URL编码URL可能会导致这样的问题:

string url = HttpUtility.UrlEncode("http://www.google.com/search?q=Example");

将产生

http 3a % 2f 2fwww。google。com % 2fsearch 3fq % 3dExample

这显然不会有很好的效果。相反,你应该在查询字符串中只编码键/值对的值,就像这样:

string url = "http://www.google.com/search?q=" + HttpUtility.UrlEncode("Example");

希望这有帮助。另外,正如teedyay提到的,您仍然需要确保非法文件名字符被删除,否则文件系统将不喜欢该路径。