使用c#从.txt文件中检索日期信息

本文关键字:检索 日期 信息 文件 txt 使用 | 更新日期: 2023-09-27 18:04:24

namespace SimpleLicense
{
class Program
{
    static void Main(string[] args)
    {
        string fileName = @"C:''Temp''test.txt";
        try
        {
            // Check if file already exists. If yes, delete it. 
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }
            // 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(31);
                sw.WriteLine("License Expires After"+" "+newDate);
                sw.WriteLine("Number of Days Remaining  ");
                sw.Close();
               // sw.WriteLine("Add ");
               // sw.WriteLine("Done! ");
            }
            // 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());
        }
    }
  }
}

.txt文件内容

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

大家好,

我已经编写了上面的代码来存储日期和时间信息到上面给出的。txt文件。我希望关于剩余天数的信息存储在.txt文件中。正如你所看到的,今天的日期是2014年5月20日,许可证将于2014年6月20日到期。因此,30应该在剩余天数旁边打印。

如果用户更改了系统时钟,并将日期更改为21-5-2014,则在剩余天数旁边应打印29Days

我还希望当应用程序在特定日期执行时,日期应设置为该日期,即安装日期,不应更改,剩余的日期应根据安装日期

计算有谁能帮我弄明白这个吗?

谢谢

使用c#从.txt文件中检索日期信息

下面的代码将给出天数:

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

可以使用下面提到的代码

var Remainingdays=(LicenseExpires-InstalledDate).TotalDays

如果你想用int天,那么

var Remainingdays=(LicenseExpires-InstalledDate).Days

我想你想做时间限制版本的软件?

虽然前面回答中的代码在技术上是正确的,但您可能不应该使用DateTime。现在作为用户可以篡改系统时钟和规避您的措施。从其他来源获取当前日期,例如:

http://www.worldtimeserver.com/

这也有缺点,比如增加了启动时间,如果页面或用户的连接断开了怎么办?

更好和更简单的解决方案是忘记时间限制和限制应用程序可以启动的次数。然后你只需在打开程序时加载数字,在关闭程序时写入减1。

此外,将相关值存储为明文(同时提供有用的用户友好描述!)可能不是一个好主意,因为任何不太懂行的用户都可能只是窥探文件并在任何文本编辑器中编辑它们。您可能想使用某种加密算法,如AES:

http://msdn.microsoft.com/pl-pl/library/system.security.cryptography.aes%28v=vs.110%29.aspx