Search code examples
c#graphqlshopify.net-4.6.1

How to escape triple quotes in C# string for the use GraphQL queries?


I am trying to run a Shopify bulkOperationRunQuery using GraphQL.Client.

The Query field needs to be set to the the below, but I am unable to set the Query field (type string) to include the triple quotes.

As an example, this is what needs to be posted, as shown on Shopify docs:

mutation {
  bulkOperationRunQuery(
   query: """
    {
      products {
        edges {
          node {
            id
            title
          }
        }
      }
    }
    """
  ) {
    bulkOperation {
      id
      status
    }
    userErrors {
      field
      message
    }
  }
}

This is the code. I've tried using backslashes, and more double quotes in attempt to escape the quotes, but I haven't been successful.

var request = new GraphQLRequest
{
    Query = @"""
        mutation {
            bulkOperationRunQuery(
            query 
            """
            {
                products {
                    edges {
                        node {
                        id
                        title
                    }
                }
                }
            }
            """
            ) {
            bulkOperation {
                id
                status
            }
        userErrors
        {
            field
            message
            }
            }
        }
        """
};


var response = await graphQlClient.SendQueryAsync<dynamic>(request);

How do I escape the triple quotes to be included in the Query string?

EDIT: This is a .NET 4.6.1 project. I am unable to use C# 11 features. Is there any other way to do this?


Solution

  • Inside a literal string (preceded with @) you can escape quotations by doubling them. Keep in mind you still need to have your opening and closing quotations, so if you need a string that starts with 3 quotes, you will have 7 as shown:

    var Query = @"""""""
      mutation {
          bulkOperationRunQuery(
          query 
          """"""
          {
      products {
        edges {
          node {
            id
            title
                  }
        }
      }
    }
    """"""
          ) {
      bulkOperation {
        id
        status
          }
      userErrors
      {
        field
        message
          }
    }
    }
      """"""";