/// <summary> /// Converts a string to an HTML-encoded string /// </summary> /// <param name="value">The string to encode</param> /// <param name="attributeQuotesType">HTML attribute quotes type</param> /// <returns>The encoded string</returns> public static string HtmlAttributeEncode(string value, HtmlAttributeQuotesType attributeQuotesType = HtmlAttributeQuotesType.Double) { char quoteCharValue = '"'; string quoteCharReference = """; // use `"` instead of `"`, because it is shorter if (attributeQuotesType == HtmlAttributeQuotesType.Single) { quoteCharValue = '\''; quoteCharReference = "'"; } if (string.IsNullOrWhiteSpace(value) || !ContainsHtmlAttributeEncodingChars(value, quoteCharValue)) { return(value); } string result; StringBuilder sb = StringBuilderPool.GetBuilder(); using (var writer = new StringWriter(sb)) { int charCount = value.Length; for (int charIndex = 0; charIndex < charCount; charIndex++) { char charValue = value[charIndex]; switch (charValue) { case '"': case '\'': if (charValue == quoteCharValue) { writer.Write(quoteCharReference); } else { writer.Write(charValue); } break; case '&': writer.Write("&"); break; case '<': writer.Write("<"); break; default: writer.Write(charValue); break; } } writer.Flush(); result = writer.ToString(); } StringBuilderPool.ReleaseBuilder(sb); return(result); }
/// <summary> /// Converts a string to an HTML-encoded string /// </summary> /// <param name="value">The string to encode</param> /// <param name="attributeQuotesType">HTML attribute quotes type</param> /// <returns>The encoded string</returns> public static string HtmlAttributeEncode(string value, HtmlAttributeQuotesType attributeQuotesType = HtmlAttributeQuotesType.Double) { char quoteCharValue = '"'; string quoteCharReference = """; // use `"` instead of `"`, because it is shorter if (attributeQuotesType == HtmlAttributeQuotesType.Single) { quoteCharValue = '\''; quoteCharReference = "'"; } if (string.IsNullOrWhiteSpace(value) || !ContainsHtmlAttributeEncodingChars(value, quoteCharValue)) { return value; } string result; using (var writer = new StringWriter()) { int charCount = value.Length; for (int charIndex = 0; charIndex < charCount; charIndex++) { char charValue = value[charIndex]; switch (charValue) { case '"': case '\'': if (charValue == quoteCharValue) { writer.Write(quoteCharReference); } else { writer.Write(charValue); } break; case '&': writer.Write("&"); break; case '<': writer.Write("<"); break; default: writer.Write(charValue); break; } } writer.Flush(); result = writer.ToString(); } return result; }