Question Read and delete contents from a text file

Joined
Apr 28, 2016
Messages
5
Programming Experience
1-3
In my vb.net application there is a requirement that the program should read the contents of a log file after every 24 hours and flush the file contents so that new logs can be added to it then.

I can easily add the timer to do this on regular time intervals but facing problems in getting the code to read and delete the contents of the log file. I am reading the contents of the file using the below code:

Using sr As New StreamReader(TextBox3.Text)
line = sr.ReadToEnd()
End Using

TextBox3 has the location of the text file defined by the user at run time.

I read this code on a different forum but it doesn't fit in my scenario although I thought this is pretty close to what I wanted. But, it reads lines and deletes by line numbers. I want to read the whole content and delete it. The reason I want to read the contents is because I want to save it in a variable and pass the variable contents to another function in the code which send this logs to a server which saves the archived logs.


  1. Dim text As Array
  2. Dim lines As New List(Of String)

  3. text = File.ReadAllLines(data_path & "notes.txt")
  4. lines.AddRange(text)
  5. Array.Clear(text, 0, text.Length)
  6. lines.RemoveAt(lines.IndexOf(value))
  7. text = lines.ToArray()
  8. file.WriteAllLines(data_path & "notes.txt", text)

 
'Read the file.
Dim fileContents = IO.File.ReadAllText(filePath)

'Clear the file.
IO.File.WriteAllText(String.Empty)
That said, if the code that writes the log creates the file if it doesn't exist then you may as well just delete the file rather than clear it.
 

Latest posts

Back
Top