【问题标题】:Append one file into another file将一个文件附加到另一个文件中
【发布时间】:2019-08-15 19:40:51
【问题描述】:

我一直在研究这个问题,我发现的所有示例都是将给定的字符串附加到文件中,但是我无法找到任何运气将整个文件附加到文件的结尾。一切都在使用不适合我需要的 .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

【问题讨论】:

  • .sgm 是否意味着它们包含 SGML?
  • 是 SGM 表示 SGML。但是就像文本文件一样,只要它们满足要求,就可以附加到一个和另一个中
  • 在我看来,Dim result = Path.GetFileName(file) Dim fileToCopy = searchDir & "\" & resultDim fileToCopy = file 相比还有很长的路要走——或者问题中省略了其他代码? (Directory.GetFiles 返回完整路径以及文件名。)
  • 我把完整路径放进去是因为代码会在我们系统的多个子文件夹中运行

标签: vb.net appendfile


【解决方案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

【讨论】:

    【解决方案2】:

    您可以将文件内容读入字符串,然后像这样使用 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 比串联字符串好一点。

    【讨论】:

    • 根据文件的大小,将整个文件加载到内存中可能不可行。更通用的方法是读取文件的块。
    • @FalcoGer 让我们担心它是否真的发生了。我们还应该检查是否有足够的可用磁盘空间。
    • 这太棒了!非常感谢。
    猜你喜欢
    • 2018-12-06
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 2018-02-07
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    相关资源
    最近更新 更多