A bit late to this question, but I created a class with all the handy methods needed to create a fully functional time trial in C#. Rather than your application config, I write the expiry time to the Windows Application Data path, and that will also remain persistent even after the program has closed (it's also tricky to find the path for the average user).
Fully documented and simple to use, I hope someone finds it useful!
public class TimeTrialManager
{
private long expiryTime = 0;
private string userPath = "";
public TimeTrialManager(string softwareName)
{
// Create folder in Windows Application Data folder for persistence:
userPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\" + softwareName + "_prefs\\";
if (!Directory.Exists(userPath)) Directory.CreateDirectory(Path.GetDirectoryName(userPath));
userPath += "expiryinfo.txt";
if (File.Exists(userPath)) expiryTime = Convert.ToInt64(File.ReadAllText(userPath));
}
// Use this method to check if the expiry has already been created. If
// it has, you don't need to call the setExpiryDate() method ever again.
// C:\Users\Dan\AppData\Roaming\SSNotify_prefs\expiryinfo.txt
public bool expiryHasBeenStored()
{
return File.Exists(userPath);
}
// Use this to set expiry as the number of days from the current time.
// This should be called just once in the program's lifetime for that user.
public void setExpiryTime(double days, double seconds = 0)
{
DateTime time = DateTime.Now.AddDays(days).AddSeconds(seconds);
expiryTime = time.ToFileTimeUtc();
try { File.WriteAllText(userPath, expiryTime.ToString()); }
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
// Check for this in a background timer or whenever else you wish to check if the time has run out
public bool trialHasExpired()
{
if (DateTime.Now.ToFileTimeUtc() >= expiryTime) return true; else return false;
}
// This method is optional and isn't required to use the core functionality of the class
// Perhaps use it to tell the user how long he has left to trial the software
public string expiryAsHumanReadableString(bool remaining = false)
{
DateTime dt = new DateTime();
dt = DateTime.FromFileTime(expiryTime); // alternative: FromFileTimeUtc
if (remaining == false) return dt.ToShortDateString() + " " + dt.ToLongTimeString();
else
{
TimeSpan ts = dt.Subtract(DateTime.Now);
if (ts.TotalSeconds < 0) return "0";
string days = "";
if (ts.Days != 0) days = ts.Days + " days + ";
return days + ts.ToString(@"hh\:mm\:ss");
}
}
}
Here is a typical usage of the above class. Couldn't be simpler!
TimeTrialManager ttm;
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
ttm = new TimeTrialManager("TestTime");
if (!ttm.expiryHasBeenStored()) ttm.setExpiryTime(0,10); // Expires in 10 seconds from creation time
}
private void timer1_Tick_1(object sender, EventArgs e)
{
if (ttm.trialHasExpired()) {
timer1.Enabled = false;
MessageBox.Show("Trial over! :(");
Environment.Exit(0);
}
}