/// <summary> /// Provides the path string escaped in a way which is correct for combining into the URI representation. /// </summary> /// <returns>The escaped path value</returns> public string ToUriComponent() { if (!HasValue) { return(string.Empty); } var value = _value; var i = 0; for (; i < value.Length; i++) { if (!PathStringHelper.IsValidPathChar(value[i]) || PathStringHelper.IsPercentEncodedChar(value, i)) { break; } } if (i < value.Length) { return(ToEscapedUriComponent(value, i)); } return(value); }
private static string ToEscapedUriComponent(string value, int i) { StringBuilder buffer = null; var start = 0; var count = i; var requiresEscaping = false; while (i < value.Length) { var isPercentEncodedChar = PathStringHelper.IsPercentEncodedChar(value, i); if (PathStringHelper.IsValidPathChar(value[i]) || isPercentEncodedChar) { if (requiresEscaping) { // the current segment requires escape if (buffer == null) { buffer = new StringBuilder(value.Length * 3); } buffer.Append(Uri.EscapeDataString(value.Substring(start, count))); requiresEscaping = false; start = i; count = 0; } if (isPercentEncodedChar) { count += 3; i += 3; } else { count++; i++; } } else { if (!requiresEscaping) { // the current segment doesn't require escape if (buffer == null) { buffer = new StringBuilder(value.Length * 3); } buffer.Append(value, start, count); requiresEscaping = true; start = i; count = 0; } count++; i++; } } if (count == value.Length && !requiresEscaping) { return(value); } else { if (count > 0) { if (buffer == null) { buffer = new StringBuilder(value.Length * 3); } if (requiresEscaping) { buffer.Append(Uri.EscapeDataString(value.Substring(start, count))); } else { buffer.Append(value, start, count); } } return(buffer.ToString()); } }