-1

我已经为此工作了一段时间,我发现的所有示例都是将给定的字符串附加到文件中,但是我无法找到在结尾附加整个文件的任何运气文件。一切都在使用 .appendAllText 或 appendText 这不适合我的需要。

我的文件是.sgm. 在我的代码中,我首先获取所有 sgm 文件,然后检查该文件是否以 _Ch# 结尾。

我准备将文件附加到主文件,但到目前为止,我所能做的就是将文件名的字符串文本附加到主文件的末尾。

非常感谢您的帮助。最大限度

Public Class Form1
Private Sub btnImport_Click(sender As Object, e As EventArgs) Handles btnImport.Click
    Dim searchDir As String = txtSGMFile.Text 'input field for user
    '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")
    Dim existingFile = searchDir & "\Bld1_Master_Document.sgm"


    'Loop through each file found by the REGEX
    For Each file In fndFiles
        If rx.IsMatch(file) Then
            If ch1.IsMatch(file) Then
                Dim result = Path.GetFileName(file)
                Dim fileToCopy = searchDir & "\" & result

                'THIS IS WHERE I WANT TO APPEND fileToCopy INTO existingFile
                System.IO.File.AppendAllText(fileToCopy, existingFile)


                MessageBox.Show("File Copied")
            End If
            'MsgBox(file)
        End If
    Next file
    Close()
End Sub
4

2 回答 2

3

您可以将文件内容读入字符串,然后像这样使用 AppendAllText:

Imports System.IO
' ...

Dim fileToCopy = Path.Combine(searchDir, result)

'THIS IS WHERE I WANT TO APPEND fileToCopy INTO existingFile
Dim fileContent = File.ReadAllText(fileToCopy)

File.AppendAllText(existingFile, fileContent)

使用Path.Combine比连接字符串要好一些。

于 2019-03-25T14:54:22.960 回答
1

您可以使用以下方法从字面上附加所有字节:

Using fs As New System.IO.FileStream(existingFile, IO.FileMode.Append)
    Dim bytes() As Byte = System.IO.File.ReadAllBytes(fileToCopy)
    fs.Write(bytes, 0, bytes.Length)
End Using
于 2019-03-25T14:55:25.187 回答