使用c#仅将日期存储到.txt文件一次

时间:2014-05-25 15:26:21

标签: c# datetime

我编写的代码将日期存储到.txt文件中,如图所示。我能够存储当前的日期和时间。我希望第一次执行应用程序时只应设置一次日期。

安装日期:设置为第一次执行应用程序的日期,不管应用程序执行的时间长短都不应更改

我正在尝试实施30天许可。我希望当应用程序第一次执行时,执行应用程序的日期应存储到.txt文件中,不应更改,以便可以在此基础上计算剩余天数。我的主要目标是阻止用户在30天后使用我的应用程序

class Program
{
    static void Main(string[] args)
    {

        string fileName = @"C:\\Temp\\test.txt";

        try
        {

            // Create a new file 
            Directory.CreateDirectory(Path.GetDirectoryName(fileName));

            using (StreamWriter sw = File.CreateText(fileName))
            {

                sw.WriteLine("Thermo Licensing System file");
                sw.WriteLine("------------------------------------");
                sw.WriteLine("Installed Date: {0}", DateTime.Now.ToString());


                DateTime newDate = DateTime.Now.AddDays(30);
                DateTime date = DateTime.Now;
                sw.WriteLine("License Expires After"+" "+newDate);

                int numberOfDays = newDate.Subtract(date).Days;
                sw.WriteLine("Number of Days Remaining: " + "  " + numberOfDays.ToString());
                sw.Close();


            }

            // Write file contents on console. 
            using (StreamReader sr = File.OpenText(fileName))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
                     Console.ReadLine();
            }
        }
        catch (Exception Ex)
        {
            Console.WriteLine(Ex.ToString());
        }
    }
}

Output (.txt file)

Thermo Licensing System file
------------------------------------
Installed Date: 20-05-2014 16:01:42
License Expires After 20-06-2014 16:01:42
Number Of Days Remaining

1 个答案:

答案 0 :(得分:1)

您已经在检查该文件是否存在,因此无需变量。

if (File.Exists(fileName)) {
    // Test to make sure the contents of the file are something you
    // created, and not another file with the same name.
}
else {
    // Continue on with your logic to create the file and add the dates.
}