[英]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.