我是VB的新手,我正在尝试将文本添加到文本文件中的特定位置。我正在尝试在“G4 K900”和“N10 G54”之间添加文字。这是我正在使用的代码。我做了谷歌搜索,但找不到任何东西,但最有可能的信息就在那里,我只是不明白。我还需要替换文字。我想出了如何做到这一点。任何帮助将不胜感激。
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()
答案 0 :(得分:1)
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())
注意:如果其他应用使用file
则无法修改