How to pass one local string into the middle of another string as a variable? .NET C#

Viewed 73

In the below example, how to change the local QNARESULTHERE.json file with the name of the qnaResult?

public async Task ITSupportIntent(IDialogContext context, LuisResult result)
{
    var qnaResult = itKB.GetAnswer(result.Query);
    if (qnaResult.StartsWith("CARD"))
    { 
        var reply = context.MakeMessage();            
        try
        {
            string json = File.ReadAllText(HttpContext.Current.Request.MapPath("~\\AdaptiveCards\\QNARESULTHERE.json"));

Sorry this question is all over the place. Context: The actual variable i needed was the QnAAnswer i believe as referenced here: Integrate QnA Maker and LUIS to distribute your knowledge base

2 Answers

It's a little unclear exactly what value you are trying to get from the result, but assuming LuisResult has a FileName property on it, as an example, you can use string interpolation (available since C# 7), like this:

string relativePath = $"~\\AdaptiveCards\\{result.FileName}.json";

You may also find that the @-style verbatim string syntax works better here, since it means you don't have to escape backslashes:

string relativePath = $@"~\AdaptiveCards\{result.FileName}.json";

If you're using an older version of C#, you can also use string.Format or just plain old string concatenation:

string relativePath = string.Format(@"~\AdaptiveCards\{0}.json", result.FileName);
string relativePath = @"~\AdaptiveCards\" + result.FileName + ".json";

Whichever you choose, you will of course want to pass the resulting value along like you were doing.

string json = File.ReadAllText(HttpContext.Current.Request.MapPath(relativePath));

You can use string.Format() like so:

string json = File.ReadAllText(HttpContext.Current.Request.MapPath(string.Format(@"~\AdaptiveCards\{0}.json", qnaResult));

Above is assuming qnaResult is a string that contains the file name you want. If it's a class instance, then use the appropriate property of it that contains the file name.

Related