【问题标题】:find character and Insert a new line in the file查找字符并在文件中插入新行
【发布时间】:2023-02-02 21:22:44
【问题描述】:

我希望逐行读取文件,一旦到达第 65 至 67 列中不包含相同字符的行,我想在其上方的第 2 行插入一个字符串行。我正在使用 VB.NET

到目前为止,我已经编写了逐行读取文件的代码。 我不确定如何将字符串行插入到第 65-67 列中的字符不同的文件中 任何帮助都会很棒。谢谢

   Protected Sub UploadFile(sender As Object, e As EventArgs)
    Dim fileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
    Dim filePath As String = Server.MapPath("~/Files/") & fileName
    FileUpload1.SaveAs(filePath)

    '--Read block of lines then insert line for each new block
    For Each line In IO.File.ReadLines(filePath)
        'If line.Substring(65, 3) <> " " Then '<> to previous substring

            '--Insert new line 

        'End If
    Next

End Sub



 <asp:FileUpload ID="FileUpload1" runat="server" />
 <asp:Button ID="Button1" Text="Upload File" runat="server" OnClick="UploadFile" />

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    像这样的东西。

        Dim lines As List(Of String) = IO.File.ReadLines(filePath).ToList
        Dim idx As Integer = 0
        Do While idx < lines.Count - 2
            Dim thisLine As String = lines(idx)
            Dim nextLine As String = lines(idx + 1)
            If thisLine.Substring(65, 3) <> nextLine.Substring(65, 3) Then
                lines.Insert(idx + 1, "NEW BLOCK")
                idx += 1
            End If
            idx += 1
        Loop
        Dim foo As String = String.Join(ControlChars.Cr, lines)
        IO.File.WriteAllText("path", foo)
    

    编辑 - 基于 cmets

        Dim lines As List(Of String) = IO.File.ReadLines(filePath).ToList
        Dim idx As Integer = 0
        Do While idx < lines.Count - 2
            Dim thisLine As String = lines(idx)
            Dim nextLine As String = lines(idx + 1)
            Dim key As String = thisLine.Substring(65, 3).Trim
            If key <> nextLine.Substring(65, 3) AndAlso
                    key = "" Then
                lines.Insert(idx + 1, "NEW BLOCK")
                idx += 1
            End If
            idx += 1
        Loop
        Dim foo As String = String.Join(ControlChars.Cr, lines)
        IO.File.WriteAllText("path", foo)
    

    【讨论】:

    • @Martha - 它旨在展示您如何解决这个问题。您可以更改支票以满足您的需要。
    • 此代码将“NEW BLOCK”添加到第二行。我应该澄清的是,我并不总是希望插入第二行。因此我不能使用 Dim nextLine As String = lines(idx + 1)。相反,我希望在 Substring(65, 3) 不是什么并且与前一个不同时插入它。此代码仅在前两行之后插入,而不是在包含 04592160 的行的前面插入
    • 谢谢你的代码。我仍然不确定如何读取行,只插入“新块”,其中 Substring(65, 3) 不为空且与最后一个不同
    • @Martha - 见上面的编辑
    猜你喜欢
    • 2021-07-26
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 2018-11-06
    • 2020-09-08
    相关资源
    最近更新 更多