Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing a text file without deleting it

Tags:

file

text

vb.net

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?

like image 895
Coding Duchess Avatar asked Dec 23 '14 14:12

Coding Duchess


2 Answers

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.

like image 120
rory.ap Avatar answered Sep 29 '22 07:09

rory.ap


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()
like image 29
Neolisk Avatar answered Sep 29 '22 08:09

Neolisk