2014-09-12 120 views
0

我有一个TXT文件,其中包含一些要替换的值。例如:读取文件,搜索文本并替换所有行

 
"FirtsColor"  "176 174 145 255" 
"SecondColor"  "204 204 145 255" 
"ThirdColor"  "164 240 115 255" 

用我的代码,我可以替换文本并添加新的值,但仍然有旧的值。

 
"FirtsColor"  "176 174 145 255" 
"SecondColor"  "255 110 195 255"  "204 204 145 255" 
"ThirdColor"  "164 240 115 255" 
Private Sub Button1_Click() Handles Button1.Click 
    If Not File = Nothing Then 
     Dim filePath As String = File 
     Dim reader As New IO.StreamReader(filePath) 
     Dim contents As String = reader.ReadToEnd() 
     reader.Close() 
     contents = contents.Replace(Chr(34) & "SecondColor" & Chr(34), Chr(34) & "SecondColor" & Chr(34) & "  " & Chr(34) & "255 110 195 255" & Chr(34)) 
     Dim writer As New IO.StreamWriter(filePath) 
     writer.WriteLine(contents) 
     writer.Close() 
    End If 
End Sub 

我想要什么?

  • (在这种情况下,“SecondColor”)搜索在整个文件中的文本
  • 新删除所有行(“SecondColor”“204 204 145 255”)
  • 写相同的字再次RGBA值(“SecondColor”“255 110 195 255”)

我用我当前的代码得到了什么?

  • 搜索整个文件( “SecondColor”)文本
  • 替换文本,并添加新的值( “SecondColor” “255 110 195 255”, “204 204 145 255”)
+0

您的问题是什么? – okrumnow 2014-09-12 14:39:37

+0

这是非常不清楚你在找什么。 – doge 2014-09-12 14:48:19

+0

你在这个文件中有多少行? – Steve 2014-09-12 14:50:35

回答

0

4000行这种类型的内存不是很大,所以你可以在内存中读取它们,并执行一个循环来搜索你的数据,用所需的值替换整行并写回到磁盘

Sub Main 
    Dim lines = File.ReadAllLines("D:\temp\testcolor.txt") 
    for x = 0 to lines.Count() - 1 
     if lines(x).Trim().StartsWith(Chr(34) & "SecondColor" & Chr(34)) Then 
      lines(x) = string.Format("{0,-20}{1}", _ 
         Chr(34) & "SecondColor" & Chr(34), _ 
         Chr(34) & "255.255.255.255" & Chr(34)) 
     End if 
    Next 
    File.WriteAllLines("D:\temp\testcolor.txt", lines) 
End Sub 

File.ReadLines将您的数据拆分成不同的行,因此很容易用您的输入替换整个行

+0

增加了一点改进,强制第一列(颜色列)中的文本为20个字符宽 – Steve 2014-09-12 16:29:22