Compare between date time now and date time add minutes then overwrite the text file

Kim

I have create one file which call total-cost.txt and I want to compare two time which is current time and time after added minutes.

I have tried and this is my code

private void OverwriteText()
{
    DateTime dn = DateTime.Now;
    DateTime now= dn.AddMinutes(2);

    if (dn > now )
    {
        dn = now;
        string txt = Convert.ToString(TotCostLong);
        using (FileStream fs = new FileStream("total-cost.txt", FileMode.Truncate))
        {
            using (StreamWriter writer = new StreamWriter(fs))
            {
                writer.Write(txt);
            }
        }
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    OverwriteText();
}

In my ideas, if the current time is reached the time which added by 2 minutes it will overwrite the textfile.

For example, current time is 11.30 and after that add 2 minutes into current time which is 11.32. After reached 11.32 the file will overwrite.

If have any ideas or solution provided, I have much appreciated it.

fenixil

As you explicitly ask to help with the time comparison option, check answer below. However, this is wasting resources and I'd recommend to use timer for that, just set its interval to 120000ms and you are done

To make your code work, you need to 'remember' current time instead of replacing it on every method call. Just put it to private field and reset it once file is written.

private DateTime _lastWriteTime = DateTime.Now;

private void OverwriteText()
{
    if ((DateTime.Now - _lastWriteTime).TotalMinutes > 2)
    {
        string txt = Convert.ToString(TotCostLong);
        File.WriteAllText("total-cost.txt", txt);
        _lastWriteTime = DateTime.Now;
    }
}

private void timer1_Tick(object sender, EventArgs e)
{
    OverwriteText();
}

Every second (interval you call OverwriteText()) you'll get current time and substract from it time when you write file last time _lastWriteTime. Result is TimeSpan, so this value will grow every second and once it is larger than 2 minutes you'll enter if block.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事