-1

我有一个字符串,用于发送到 mailto。

我想找到所有特殊字符,然后将它们转义,以使我的邮件正常工作,而无需避免选择编写特殊字符。

例如,如果我的字符串包含 a #,我的 mailto 的正文将在它之前停止。

String strCmd = String.Format("window.open(\"mailto:{0}?subject={1}&body={2}\");",
                    toEmail, subject, body);

如果我的弦体是这样的:

body = "This is a string to test c# code with a mailto";

然后 mailto 将包含This is a string to test c.

我该如何解决这个问题,以获得This is a string to test c# code with a mailto

如果有的话,它也必须制作 backLine。

谢谢你。

4

1 回答 1

4

This is not really about escaping special characters but encoding a string as a valid URL than can be handled by the javascript call window.open. Even "normal" characters like <, >, are considered special when working with URLs.

Luckily, .NET can already encode a string as a URL with HttpUtility.UrlEncode. This call will replace special characters like < and > with their URL encode values %3c and %3e.

You should take care to encode only the parameters you pass to String.Format, not the entire formatted string, as UrlEncode will encode the entire string, including the ? and & characters:

String strCmd = String.Format("window.open(\"mailto:{0}?subject={1}&body={2}\");",
                HttpUtility.UrlEncode(toEmail), 
                HttpUtility.UrlEncode(subject), 
                HttpUtility.UrlEncode(body)); 
于 2013-06-14T13:25:55.213 回答