3

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.

Filburt
  • 17,626
  • 12
  • 64
  • 115

2 Answers2

4

Use a Timer, and set its Elapsed event's callback to the file cleaning method.

var timer = new Timer(10000);
timer.Elapsed += (s, e) => File.Delete("C:\\your_file.txt");
timer.Enabled = true;

If you ever need to stop the timer, set timer.Enabled to false.

Kilazur
  • 3,089
  • 1
  • 22
  • 48
1

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.

Community
  • 1
  • 1
hcham1
  • 1,799
  • 2
  • 16
  • 27