Overwrite a specific line in a text file using VB.NET
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.
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)
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:
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)
One quick way is to use readAllLines and 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.
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] = ")
)
In this loop you should be writing out all other lines and when you are on this [Path] line, print out the modified one.
So in code (sorry, it is in 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.
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.
First build a function to give the value of line '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
精彩评论