Search code examples
c#text

Delete a list in txt file which are older than today's date


My C# program has a function which appends this lists in a program real-time. My program is return a list of values date, name and status.

Do you have any idea how to append only the list with the latest time?

This is my C# code

System.IO.File.AppendAllText("rn_agent.txt", DateTime.Now.ToString("yyy-MM-dd HH:mm:ss") 
           + Environment.NewLine 
           +  name 
           + Environment.NewLine + status + Environment.NewLine);

rn_agent.txt

2022-05-26 13:57:29
Dannie Delos Alas
Available
2022-05-26 13:57:29
Krishian Santos
Available
2022-05-26 13:57:29
Puja Pal
Unavailable
2022-05-27 14:43:42
Maricar De Mesa
Occupied
2022-05-27 14:43:42
Pula Al
Occupied
2022-05-27 14:43:42
Marjorie Cacayan
Unavailable

Solution

  • You should use File.WriteAllText() method instead of File.AppendAllText(), to write latest data into the file.

    var newText = $"{DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")} \n {name} \n {statu} \n";
    System.IO.File.WriteAllText("rn_agent.txt",newText);
    

    What is difference between File.WriteAllText() and File.AppendAllText()?

    File.WriteAllText():

    Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.

    File.AppendAllText():

    Opens a file, appends the specified string to the file, and then closes the file.


    Update:

    If you want to store all the records which available for today then try below code,

    var today = DateTime.Today.ToString("yyy-MM-dd HH:mm:ss");
    var newTextList = new List<string>();
    
    //Dummy foreach loop
    foreach(var data in agentsData)
    {
       newTextList.Add($"{today} \n {data.Name} \n {data.Status}");
    }
    
    System.IO.File.WriteAllLines("rn_agent.txt", newTextList);