This is a follow on question to a post I made. https://stackoverflow.com/questions/...40628#55340628

I need to search the master document for entities...&CH1.sgm - &CH33.sgm
Mark where they are in the master document and replace the entity call with the matching file "Chapter1.sgm" found in "fnFiles". I can change the file names and entities to anything if that will help.

My code copies the text of a file and appends it to the bottom of the master_document.sgm. But now I need it to be more intelligent. Search the Master document for entity markers, then replace that entity marker with that file contents match. The file number and entity number match up. e.g.(&CH1; and Bld1_Ch1.sgm)

Thank you for all your help. You guys are great


Code:
    Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
        Dim searchDir As String = txtSGMFile.Text 'Input field from form
        Dim masterFile = "Bld1_Master_Document.sgm"
        Dim existingFileMaster = Path.Combine(searchDir, masterFile)

        'Read all lines of the Master Document
        Dim strMasterDoc = File.ReadAllText(existingFileMaster) '// add each line as String Array.

        '?search strMasterDoc for entities &Ch1.sgm
        '?replace entity name "&Ch1.sgm" with content of file "Bld1_Ch1.sgm" this content if found below
        '? do I use a book mark? Replace function?


        'Get all the sgm files in the directory specified
        Dim fndFiles = Directory.GetFiles(searchDir, "*.sgm")
        'Set up the regular expression you will make as the condition for the file
        Dim rx = New Regex(".*_Ch\d\.sgm")
        Dim ch1 = New Regex(".*_Ch[1]\.sgm")
        'Use path.combine for concatenatin directory together

        'Loop through each file found by the REGEX
        For Each fileNo In fndFiles
            If rx.IsMatch(fileNo) Then
                If ch1.IsMatch(fileNo) Then
                    Dim result = Path.GetFileName(fileNo)
                    'Use path.combine for concatenatin directory together
                    Dim fileToCopy = Path.Combine(searchDir, result)

                    'This is the file we want to copy into MasterBuild but at specific location.
                    'match &ch1.sgm inside strMasterDoc

                    Dim fileContent = File.ReadAllText(fileToCopy)

                    'Search master file for entity match then append all content of fileContent


                    File.AppendAllText(existingFileMaster, fileContent)

                    MessageBox.Show("File Copied")
                End If
            End If
        Next
        Close()
    End Sub