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

192 Views Asked by At

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?

2

There are 2 best solutions below

2
Tarazed On BEST ANSWER

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
      }
}
}
  """"""";
3
Christian Held On

Instead of escaping """, start and end your string with four quotes like this:

var myStringWithTripleQuotes = """" """ """";

You're allowed more than three consecutive characters to start and end the sequence in order to support string literals that contain three (or more) repeated quote characters.

See https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#raw-string-literals