Search code examples
c#twitch

Clear File Contents After X Amount Of Time


I need a way of clearing a text file after a certain period of time. This is what I have so far

List<string> previousWeaponList = new StreamWriter("PreviousList.txt");

So this is reading the previous weapon list into the file after a weapon is requested the weapon is written to that list. Once I do this I have a file which will get full very quickly if I save every single request, which is why I need to clean it out every X amount of time.

Would it be possible to do it like this?

private Thread fileCleaner;
public void FileCleaner()
{
    fileCleaner = new Thread(new ThreadStart(this.Run))
}

Then just have a run function which if it's true it will just write to the file and then use a

Thread.Sleep();

I heard using Threads for time isn't a good idea, but I am not an expert on this.


Solution

  • Very similar question and answer here:

    Delete files from the folder older than 4 days

    Relevant answer:

    I would recommend using a System.Threading.Timer for something like this. Here's an example implementation:

    System.Threading.Timer DeleteFileTimer = null;
    
    private void CreateStartTimer()
    {
     TimeSpan InitialInterval = new TimeSpan(0,0,5);
     TimeSpan RegularInterval = new TimeSpan(5,0,0);
    
     DeleteFileTimer = new System.Threading.Timer(QueryDeleteFiles, null, 
            InitialInterval, RegularInterval);
    
    }
    
    private void QueryDeleteFiles(object state)
    {
      //Delete Files Here... (Fires Every Five Hours).
      //Warning: Don't update any UI elements from here without Invoke()ing
      System.Diagnostics.Debug.WriteLine("Deleting Files...");
    }
    
    private void StopDestroyTimer()
    {
      DeleteFileTimer.Change(System.Threading.Timeout.Infinite,
      System.Threading.Timeout.Infinite);
    
      DeleteFileTimer.Dispose();
    }
    

    This way, you can run your file deletion code in a windows service with minimal hassle.