简体   繁体   中英

add text to specific location in a txt file in vb.net

I am new to VB and I am trying to add text to a specific location in the text file. I'm trying to add text in between "G4 K900" and "N10 G54". Here is the code I'm working with. I did a Google search but couldn't find anything, but most likely the information was there I just didn't understand it. I also needed to replace text. I figured out how to do that one. Any help would be greatly appreciated.

G90
S12000 M3 M31 M32
G4 K900
N10 G54

Public Sub BtnRun_Click(sender As System.Object, e As System.EventArgs) Handles BtnRun.Click

    Dim myStreamReaderL1 As System.IO.StreamReader
    Dim myStream As System.IO.StreamWriter

    Dim myStr As String
    myStreamReaderL1 = System.IO.File.OpenText("C:\temp/test1.out")
    myStr = myStreamReaderL1.ReadToEnd()
    myStreamReaderL1.Close()

    myStr = myStr.Replace("G90", "G100")

    'Save myStr
    myStream = System.IO.File.CreateText("C:\temp\test1.out")
    myStream.WriteLine(myStr)
    myStream.Close()
 Dim newfile As New List(Of String)()

    For Each line As String In System.IO.File.ReadAllLines("C:\temp\test1.out")
        Dim matchFound As Boolean
        matchFound = line.Contains("G4 K900")

        If matchFound Then
          newfile.Add(line & vbNewLine & "TEXTYOUWANTTOADD")
        Else
            newfile.Add(line)
        End If

    Next
File.Delete("C:\temp\test1.out")
 System.IO.File.WriteAllLines("C:\temp\test1.out", newfile.ToArray())

Note: if the file is used by other application you can not modify it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM