【问题标题】:Read and Write to specific line in textfile with VB.Net使用 VB.Net 读取和写入文本文件中的特定行
【发布时间】:2015-04-10 18:00:44
【问题描述】:

所以这是我的问题: 第一次我需要读取一个文本文件并获取第 5 行

System.IO.File.ReadAllText("E:\myFile.txt")

我的文本文件是这样的:

ABCDE "2015"
GDFTHRE "0.25 0.25"
TRYIP "192.168.1.6"
WIDTH "69222"
ORIGIN "200"

所以,我需要的是替换值 200,假设为 250 并保持如下:ORIGIN "250"

我已经尝试过替换,但我无法得到它。

【问题讨论】:

    标签: vb.net


    【解决方案1】:

    如果你的文本文件被分成几行并且你只想看第 5 行,你可以使用 ReadAllLines 将这些行读入一个字符串数组。处理第 4 行(第 5 行)并使用 WriteAllLines 重写文件。以下示例检查文件是否包含至少 5 行,并且第 5 行是否以“ORIGIN”开头;如果是这样,它将用 ORIGIN "250" 替换该行并重新写入文件。

    Dim filePath As String = "E:\myFile.txt"
    Dim lines() As String = System.IO.File.ReadAllLines(filePath)
    If lines.Length > 4 AndAlso lines(4).StartsWith("ORIGIN ") Then
        lines(4) = "ORIGIN ""250"""
        System.IO.File.WriteAllLines(filePath, lines)
    End If
    

    【讨论】:

      【解决方案2】:

      您可以简单地替换文本,然后将所有内容再次写回文件:

      Dim content As String
      
      ' read all text from the file to the content variable
      content = System.IO.File.ReadAllText("E:\myFile.txt")
      
      ' replace number, text, etc. in code
      content = content.Replace("<string to replace>","<replace with>")
      
      ' write new text back to the file (by completely overwriting the old content)
      System.IO.File.WriteAllText("E:\myFile.txt",content)
      

      【讨论】:

        猜你喜欢
        • 2020-02-06
        • 1970-01-01
        • 2016-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多