使用 VB.NET 覆盖文本文件中的特定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2050054/
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-09 14:36:30  来源:igfitidea点击:

Overwrite a specific line in a text file using VB.NET

vb.netparsing

提问by Niphoet

I need to do the following:

我需要执行以下操作:

Change the line in a text file

更改文本文件中的行

[Path] = "c:\this\certain\path\"

with this line

用这条线

[Path] = "c:\that\other\newer\path\"

These paths will most certainly be different lengths, so I need to either replace what's in the quotes or erase the line completely and enter a new one, but in the same spot, not appended to the end of the document.

这些路径肯定会有不同的长度,所以我需要替换引号中的内容或完全擦除该行并输入一个新的,但在同一位置,而不是附加到文档的末尾。

回答by Raymond C Borges Hink

This will do the trick

这将解决问题

    Dim thefile As String = "filepath"
    Dim lines() As String = System.IO.File.ReadAllLines("filepath")

    lines(number of line you want to replace) = "write what you want to replace here"

    System.IO.File.WriteAllLines(filepath, lines)

回答by alex

If you really know exactly how the line you want to replace looks and the file you're reading isn't really big, you could try to just use Replace() to add the new line instead of the old one:

如果您真的很清楚要替换的行的外观并且您正在阅读的文件不是很大,则可以尝试仅使用 Replace() 添加新行而不是旧行:

Dim reader As New StreamReader("foo.txt")
Dim writer As New StreamWriter("output.txt")

Dim s = reader.ReadToEnd().Replace("[Path]: C:\oldPath\file.txt", "[Path]: C:\newPath")
writer.Write(s)

回答by Axarydax

Read the text file into a string, iterate over each line and check if it's in the format:

将文本文件读入一个字符串,遍历每一行并检查它是否采用以下格式:

[Path] = "...."(with regular expressions or simply with string.StartsWith("[Path] = "))

[Path] = "...."(使用正则表达式或简单地使用string.StartsWith("[Path] = ")

In this loop you should be writing out all other lines and when you are on this [Path] line, print out the modified one.

在这个循环中,你应该写出所有其他行,当你在这个 [Path] 行上时,打印出修改过的行。

So in code (sorry, it is in C#):

所以在代码中(对不起,它是在 C# 中):

var reader = File.OpenText("foo.txt"); 
var writer = new StreamWriter("output.txt");
string line;
while ((line=reader.ReadLine()) != null)
{
    if (line.StartsWith("[Path]"))
        writer.WriteLine("[Path] = \"c:\that\other\newer\path\\"");
    else
        writer.WriteLine(line);
}

of course, close and dispose the StreamReader and StreamWriter.

当然,关闭配置StreamReader和StreamWriter。

回答by Joel Coehoorn

Here's the deal: due to the way files are stored on disk, you can't write to one line without also updating every line that follows it.

交易是这样的:由于文件存储在磁盘上的方式,你不能写入一行而不更新后面的每一行。

There are number of ways to do this, and the one most appropriate for your situation will depend on things like the size of the file, are you doing this to a lot of files, where in the file you expect to find this, etc.

有多种方法可以做到这一点,最适合您情况的方法取决于文件大小、您是否对大量文件执行此操作、您希望在文件中的哪个位置找到它等。

But most of the time what I like to do is actually create a copy of the old file... So as I seek through the file looking for the line(s) I need to change, I'm also writing what I've read to a new location. When I find the line, I write out the new information. I then keep seeking through the file until I reach the end at which time I close both streams, delete the original, and rename the new one.

但大多数时候我喜欢做的实际上是创建旧文件的副本......所以当我在文件中寻找我需要更改的行时,我也在写我已经读取到新位置。当我找到该行时,我会写出新信息。然后我继续查找文件,直到到达结尾,此时我关闭两个流,删除原始流,并重命名新流。

回答by xpda

One quick way is to use readAllLines and WriteAllLines:

一种快速的方法是使用 readAllLines 和 WriteAllLines:

Dim ss() As String
ss = File.ReadAllLines([path])
ss(47) = "c:\that\other\newer\path\"
File.WriteAllLines([path], ss)

If you don't know which line to change, you can search through the array ss for it.

如果您不知道要更改哪一行,可以在数组 ss 中搜索它。

回答by user3982452

First build a function to give the value of line 'n':

首先构建一个函数来给出第 'n' 行的值:

Public Function daValorConfig(ByVal numValor As Long, ByVal nomeFicheiroINI As String) As String
    Dim reader As StreamReader = New StreamReader(Application.StartupPath & "\" & nomeFicheiroINI & ".ini")
    Dim valor As String = ""
    daValorConfig = ""
    Dim i As Long = 1
    Try
        While i <= numValor
            valor = reader.ReadLine()
            i = i + 1
        End While
        daValorConfig = valor
        reader.Close()
    Catch ex As Exception
        reader.Close()
        MessageBox.Show(ex.Message, "Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Err.Clear()
    End Try
End Function

Then build a procedure that writes the new value on the specified line or keep the old one if the line is not the one you specify:

然后构建一个过程,将新值写入指定行,如果该行不是您指定的行,则保留旧值:

Public Sub guardaValorConfig(ByVal dados As String, ByVal numValor As Long, ByVal nomeFicheiroINI As String)

    Dim writer As StreamWriter = New StreamWriter(Application.StartupPath & "\" & nomeFicheiroINI & ".ini")
    Dim valor As String = ""
    Dim i As Long = 1
    Try
        While i <= numValor
            If i = numValor Then
                writer.Write(dados)
            Else
                writer.Write(daValorConfig(i, nomeFicheiroINI))
            End If
            i = i + 1
        End While
        writer.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Err.Clear()
    End Try
End Sub