Delete a text file without deleting it

I have a text file to which I will add data (so I can’t just overwrite the file). The fact is that initially it contains content that I don’t want, so before I start adding new data. Is there a way to clear a file without having to delete it and then recreate it?

+4
source share
3 answers

You can start by overwriting the file with an empty string, and then add your data afterwards. You can use this to overwrite a file:

System.IO.File.WriteAllText(Path, "")

, .

+6

, .NET , . , - File.WriteAllText. , , . File.Create - . ( ), , . 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()
+1

http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength(v=vs.110).aspx

FileStream.SetLength(0);

Set FileStream to zero. I have included documents from MSDN.

0
source

Source: https://habr.com/ru/post/1568758/


All Articles