简体   繁体   中英

How to rewrite a line in VB using StreamRead/StreamWrite

It is a very basic code that I'm using for my college coursework. Unfortunately, we're only allowed to use StreamRead and StreamWrite type functions for marking reasons. I'm unsure as to how to basically rewrite the line already in the file with a new value. I know I could delete the file and recreate but we also get marked down for that sort of thing. Any ideas?

Private Function WriteTaxableIncome()
    Dim TaxableIncomeStreamWriter As IO.StreamWriter
    TaxableIncomeStreamWriter = New IO.StreamWriter("C:\Computing\Coursework\TaxableIncome.txt", True)
    TaxableIncomeStreamWriter.WriteLine(TaxableIncome)
    TaxableIncomeStreamWriter.Close()
End Function

When you create the StreamWriter instance, you have called the constructor with New (path As String, append As Boolean) , and passed True into the append argument, so that will make the writer append to the file, instead of overwrite it. Seems like the exact opposite of what you want to do. Instead, pass False . Also, use a Using block which will Open and Close the writer. It automatically calls Dispose so you can be sure no part of it is left open.

Using writer As New IO.StreamWriter("C:\Computing\Coursework\TaxableIncome.txt", False)
    writer.WriteLine(TaxableIncome)
End Using

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM