Append one file into another file

社会主义新天地 提交于 2019-12-13 09:40:13

问题


I've been working on this for a bit and all the examples I've found have been to append a given string into the file, but I haven't been able to find any luck with appending a whole file at the end of a file. Everything's been using .appendAllText or appendText which doesn't suit my needs.

My files are .sgm. In my code I first grab all the sgm files, then I check if that file ends with _Ch#.

I'm ready to append the file to the master, but so far all I've been able to do is append the string text of the file name to the end of the master.

Your help is really appreciated. Max

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

回答1:


You can read the file content into a string and then use AppendAllText like this:

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)

Using Path.Combine is a bit better than concatenating strings.




回答2:


You can literally append all bytes using an approach like this:

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


来源:https://stackoverflow.com/questions/55339930/append-one-file-into-another-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!