vb.net 扫描包含给定字符串的行的文本文件,并用另一个字符串替换该行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15572061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:55:25  来源:igfitidea点击:

Scan text file for line containing a given string and replace the line with another string

vb.netfile

提问by 0867532

I want to scan my file for line that contains a particular string "black=" and if there is a match replace it with "blah blah" but I don't know how to do that. Here is what I tried but it does not work.

我想扫描我的文件中包含特定字符串“black=”的行,如果有匹配项,请将其替换为“blah blah”,但我不知道该怎么做。这是我尝试过但不起作用的方法。

Dim myStreamReaderL1 As System.IO.StreamReader
myStreamReaderL1 = System.IO.File.OpenText("C:\File.txt")
myStreamReaderL1.ReadLine()
If myStreamReaderL1.ReadLine.Contains("black=") Then
    Button2.Hide()
Else
    Return
End If

回答by George

Assuming the input file is not huge, you can read the whole file into a string and change all instances of black=to blah blah

假设输入文件不是很大,你可以读取整个文件转换成字符串,并更改的所有实例black=blah blah

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

        Dim myStr As String
        myStreamReaderL1 = System.IO.File.OpenText("C:\File.txt")
        myStr = myStreamReaderL1.ReadToEnd()
        myStreamReaderL1.Close()


        myStr = myStr.Replace("black=", "blah blah")
        'Save myStr
        myStream = System.IO.File.CreateText("C:\FileOut.txt")
        myStream.WriteLine(myStr)
        myStream.Close()

EDIT:a slightly more efficient (less code) version with ReadAllText per Christian Sauer's suggestion.

编辑:根据Christian Sauer的建议,使用 ReadAllText 的稍微更高效(更少代码)的版本。

EDIT2:if I am trying to be efficient, lets optimize everything. One line is enough, me thinks.

EDIT2:如果我想提高效率,让我们优化一切。一根线就够了,我想。

If you want to save into a file:

如果要保存到文件中:

        System.IO.File.WriteAllText("C:\FileOut.txt", System.IO.File.ReadAllText("C:\File.txt").Replace("black=", "blah blah"))

If you simply want to store into a string to be used later:

如果您只是想存储到一个字符串中以备后用:

        Dim myStr As String = System.IO.File.ReadAllText("C:\File.txt").Replace("black=", "blah blah")