C# txt格式记录时间,时间对比,决定是否更新代码记录Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace fileIO
{
    class Program
    {
        static void Main(string[] args)
        {
            string filename =AppDomain.CurrentDomain.BaseDirectory+ "companyUpdateLog.txt";
            if (File.Exists(filename))
            {
                string time=ReadLog(filename);
                if (time != "") {
                    DateTime dt;
                    if (DateTime.TryParse(time, out dt)) {
                        DateTime dtnow = DateTime.Now;
                        int days = (dtnow - dt).Days;
                        if (days == 7)
                        {
                            //开始更新
                            Console.WriteLine("正在更新");
                            WriteLog(filename, dtnow.ToString("yyyy-MM-dd HH:mm:ss"));
                        }
                        else {
                            Console.WriteLine("无需更新");
                        }
                    }
                }
            }
            else {
                DateTime dtnow = DateTime.Now;
                //开始更新
                Console.WriteLine("文件不存在时候:正在更新");
                WriteLog(filename, dtnow.ToString("yyyy-MM-dd HH:mm:ss"));
            }
        

            Console.ReadLine();
        }

      public static  void WriteLog(string path,string text) {
          using (FileStream file = new FileStream(path, FileMode.OpenOrCreate))
            {
                StreamWriter sw = new StreamWriter(file);
                sw.Write(text);
                sw.Close();
            }
        }
      public static string ReadLog(string path)
      {
          string a="";
          using (FileStream file = new FileStream(path, FileMode.Open))
          {
              StreamReader sw = new StreamReader(file);
              a=sw.ReadToEnd();
              sw.Close();
          }
          return a;
      }

  

你可能感兴趣的:(demo)