簡體   English   中英

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

[英]Overwrite a specific line in a text file using VB.NET

我需要做以下事情:

更改文本文件中的行

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

用這條線

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

這些路徑肯定會有不同的長度,所以我需要更換引號中的內容或完全刪除行並輸入一個新的,但是在同一個地方,不要附加到文檔的末尾。

這樣就可以了

    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)

如果您確切地知道要替換的行看起來如何,並且您正在閱讀的文件不是很大,您可以嘗試使用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)

將文本文件讀入一個字符串,遍歷每一行並檢查它是否采用以下格式:

[Path] = "...." (使用正則表達式或只使用string.StartsWith("[Path] = ")

在此循環中,您應該寫出所有其他行,當您在此[Path]行時,打印出已修改的行。

所以在代碼中(抱歉,它在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);
}

當然,關閉並處理StreamReader和StreamWriter。

這是交易:由於文件存儲在磁盤上的方式,你不能寫入一行而不更新后面的每一行。

有很多方法可以做到這一點,最適合你情況的方法將取決於文件的大小,你對很多文件這樣做,你希望在文件中找到這個,等等。

但是大多數時候我喜歡做的是創建一個舊文件的副本......所以當我通過文件尋找我需要更改的行時,我也在寫我的內容讀到新位置。 當我找到這條線時,我會寫出新的信息。 然后我繼續搜索文件,直到我到達結束時,我關閉兩個流,刪除原始文件,並重命名新文件。

一種快捷方法是使用readAllLines和WriteAllLines:

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

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

首先構建一個函數來給出'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

然后構建一個將新值寫入指定行的過程,或者如果該行不是您指定的行,則保留舊值:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM