save the file in 1 min interval if some changes happened in wpf c#

664 Views Asked by At

I have a xml file which i have to load in richtextbox in wpf. if some changes occure in txt file then it will save in different path automatically after a time interval of 1 min. Let the 1st changes happens in 10:11 then all the changes made up to 10:12 will save.File creation time will be 10:12 then again the richtextbox will be modified at 10:50 then the file modified time will be 10:51.The loading and the saving path is different.

  private void startSaveTimer()
    {
        Timer saveTimer = new Timer(60000);
        saveTimer.Elapsed += saveTimer_Elapsed;
        saveTimer.Start();
    }

    private void saveTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        string filepath = @"C:\mydoc.txt";//file save path
        if (File.Exists(filepath))
        {
            FileStream file = new FileStream(filepath, FileMode.Open);
            //geting the content  from file and compare with richtextbox data
            //if not same then saving it again
        }
       else
       {
        //save file
       }
    }

    private void richText_TextChanged(object sender, TextChangedEventArgs e)
    {
        startSaveTimer();
    }

but this code calledin each single changed so
FileStream file = new FileStream(filepath, FileMode.Open); is showing error as used by different user. try to keep lock still got the same error.

1

There are 1 best solutions below

1
On

See the following:

WPF Timer Like C# Timer

This gives you an event to fire your saves. I think you are also saying you only want to save when a change has occurred. So, you'll want to set some sort of dirty flag when the user makes a change so the timer event can check it, save, and reset it.

UPDATE: I think I understand your requirements better now. Since you just want a delayed save (not saving every minute), you could just do something like this:

private bool _isSaving = false;

private void richText_TextChanged(object sender, TextChangedEventArgs e)
{            
    delayedSaveAsync();
}

private async void delayedSaveAsync()
{
    // if already waiting, get out
    if (_isSaving) return;

    _isSaving = true;
    await Task.Delay(60000);

    // save

    _isSaving = false;
}

You need to keep track if you are already saving, or every keystroke is going to spawn another saving thread.