I have a text file to which I will be appending data(hence I can't just overwrite the file). The thing is that originally it does contain content I do not want, so before I start appending new data. Is there a way to clear the file without having to delete and then re-create it?
You can start by overwriting the file with an empty string, and then append your data afterwards. You could use this to overwrite the file:
System.IO.File.WriteAllText(Path, "")
The benefit of this as opposed to deleting and recreating the file is that you will preserve the original create date of the file along with any other metadata.
Yes, most .NET methods allow you to either append or overwrite. You already found one method that could do it - File.WriteAllText. The only drawback is that it's non-streamed, so for a lot of content, you may need a lot of memory. File.Create is a stream version. It may look like more code (and it is), but it can be useful in situations when you simply cannot afford to put all your contents in memory at once. Example from MSDN:
Dim path As String = "c:\temp\MyTest.txt"
' Create or overwrite the file.
Dim fs As FileStream = File.Create(path)
' Add text to the file.
Dim info As Byte() = New UTF8Encoding(True).GetBytes(
"This is some text in the file.")
fs.Write(info, 0, info.Length)
fs.Close()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With