Results 1 to 3 of 3

Thread: Create Interpolated String From a File

  1. #1

    Thread Starter
    New Member
    Join Date
    Jun 2024
    Posts
    2

    Create Interpolated String From a File

    I have lengthy email body templates that I keep in separate data files. These templates contain the String.Format parameters {0}, {1}, etc. As I have numerous of these variables it becomes cumbersome and error prone to use String.Format. I would like to put named variables in the template files. I can't figure out how to do this with an interpolated string as I can't create an interpolated string from a string variable.

    Can anyone think of a good way to accomplish this?

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    12,087

    Re: Create Interpolated String From a File

    Basically you're wanting to build a mail merge. I've done this in the past by setting up a dictionary where the key represents the mail merge parameter and the value represents the value needed to be injected into the body. I tended to wrap the keys in square brackets but you could use curly brackets like in your String.Format style.

    Take a look at this example:
    Code:
    Private Function ReplaceMailMerge(body As String) As String
        Dim supportedMailMergeParameters = New Dictionary(Of String, String)() From {
            {"Mail Merge 1", "Foo"},
            {"Mail Merge 2", "Bar"},
            {"Etc", "Etc..."}
        }
    
        For Each supportedMailMergeParameter In supportedMailMergeParameters
            Dim mailMergeParameter = $"{{{supportedMailMergeParameter.Key}}}"
            Dim mailMergeValue = supportedMailMergeParameter.Value
    
            body = body.Replace(mailMergeParameter, mailMergeValue)
        Next
    
        Return body
    End Function
    Using that Function would turn this string:
    Code:
    Oh {Mail Merge 1}, can I just get a {Mail Merge 2} or {Etc}
    Into this:
    Code:
    Oh Foo, can I just get a Bar or Etc...
    Live Demo: https://dotnetfiddle.net/9rpDwB
    Last edited by dday9; Jun 13th, 2024 at 09:38 AM.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  3. #3

    Thread Starter
    New Member
    Join Date
    Jun 2024
    Posts
    2

    Re: Create Interpolated String From a File

    Thanks. I think that will work for me.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width