【发布时间】:2019-03-26 07:08:47
【问题描述】:
这是对我发布的帖子的后续问题。 Append one file into another file
我需要在主文档中搜索实体"&CH1.sgm" 到"&CH33.sgm",
标记它们在主文档中的位置,并将实体调用替换为“fnFiles”中的匹配文件"Chapter1.sgm"。如果有帮助,我可以将文件名和实体更改为任何内容。
我的代码复制文件的文本并将其附加到 master_document.sgm 的底部。但现在我需要它更智能。在主文档中搜索实体标记,然后将该实体标记替换为该文件内容匹配。文件编号和实体编号匹配。例如(&CH1; 和 Bld1_Ch1.sgm)
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
【问题讨论】:
-
IMO,您应该使用正则表达式在您的主文档中查找匹配模式(
&CH1.sgm、&CH2.sgm等)。Regex.Matches返回匹配的集合,它报告在字符串中找到匹配的索引位置以及(除其他外)匹配模式的长度。然后您可以使用这些信息将Insert一个字符串(对应于外部文件内容)中的引用位置。使用找到的模式加载相关的文本文件。使用StringBuilder而不是简单的string来保存文件内容。 -
看起来您刚刚粘贴了另一个问题的固定代码,但我没有看到任何尝试实现您的新要求的痕迹。尝试自己解决问题,然后返回遇到的任何具体问题。
-
我一直在研究它并在网上搜索答案。我发布的是我文件的最干净版本,因此您不会看到我之前的所有尝试和错误。我不会只是粘贴代码并期望每个人都为我编写它。但我很感激你想让我诚实。最大
标签: vb.net