private static string EscapeProductInformation()

in src/Custom/Internal/TelemetryDetails.cs [85:140]


    private static string EscapeProductInformation(string productInfo)
    {
        // If the string is already valid, we don't need to escape anything
        bool success = false;
        try
        {
            success = ProductInfoHeaderValue.TryParse(productInfo, out var _);
        }
        catch (Exception)
        {
            // Invalid values can throw in Framework due to https://github.com/dotnet/runtime/issues/28558
            // Treat this as a failure to parse.
        }
        if (success)
        {
            return productInfo;
        }

        var sb = new StringBuilder(productInfo.Length + 2);
        sb.Append('(');
        // exclude the first and last characters, which are the enclosing parentheses
        for (int i = 1; i < productInfo.Length - 1; i++)
        {
            char c = productInfo[i];
            if (c == ')' || c == '(')
            {
                sb.Append('\\');
            }
            // If we see a \, we don't need to escape it if it's followed by a '\', '(', or ')', because it is already escaped.
            else if (c == '\\')
            {
                if (i + 1 < (productInfo.Length - 1))
                {
                    char next = productInfo[i + 1];
                    if (next == '\\' || next == '(' || next == ')')
                    {
                        sb.Append(c);
                        sb.Append(next);
                        i++;
                        continue;
                    }
                    else
                    {
                        sb.Append('\\');
                    }
                }
                else
                {
                    sb.Append('\\');
                }
            }
            sb.Append(c);
        }
        sb.Append(')');
        return sb.ToString();
    }