arraysvb.netappendtxt

Append Text With Newest Entry On Top


I have this code to save data in array as txt file on computer.

 Dim path As String = "C:\Users\Desktop\Test.txt"

 Dim appendText As String = (Array(0) & Now & Environment.NewLine)
 File.AppendAllText(path, appendText, Encoding.UTF8)
 Dim readText As String() = File.ReadAllLines(path, Encoding.UTF8)

 For Each s As String In readText
     Console.WriteLine(s)
 Next

Is there a way to append text with newest entry on top? I was thinking kind of how you can make a data log by shifting data between 2 arrays Ex:

    Array.Copy(Array1, Array2, 100)
    Array.Copy(Array2, 0, Array1, 1, 100)

Is there a way to do same thing but with txt files?


Solution

  • How about something like so:

    Dim path As String = "C:\Users\Desktop\Test.txt"
    Dim newEntry As String = Array(0) & Now & Environment.NewLine
    Dim oldText As String = ""
    If File.Exists(path) Then oldText = File.ReadAllText(path, Encoding.UTF8)
    File.WriteAllText(path, newEntry & oldText, Encoding.UTF8)
    

    This way you will have the newest entry at the top of the file.