检查文件的存在和修改日期

本文关键字:修改 日期 存在 文件 检查 | 更新日期: 2023-09-27 18:20:13

我正在创建一个使用从Random.org中提取的数据的脚本。我很难弄清楚如何在不重复脚本中的文件创建部分的情况下使其工作。我想做的是,如果文件不存在如果文件超过24小时,则创建一个新文件。

using UnityEngine;
using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using TrueRNG;
public class Player : MonoBehaviour {
    private Transform TS;
    public int pspeed = 20;
    public static int playerLives = 3;
    public static int score = 0;
    float timer = 0f;
    string trgd = "R:''trrnd.txt";
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    public GameObject LaserFab; //variable to reference prefab.
    // Use this for initialization
    void Start () {
        TS = transform;
        TS.position = new Vector3(0, -14.78957f, 0); //Spawn point
        if (File.Exists(trgd))
        {
            print("The file exists! Checking time since creation...");
            //Get date from existing file.
            string[] lines = File.ReadAllLines(trgd); 
            print(lines[0]);
            DateTime genDate = Convert.ToDateTime(lines[0]);
                //Is existing data more than 1 day old?
                if (genDate.AddDays(1) > DateTime.UtcNow)
                {
                    print("Random data is old, creating new file...");
                }
        //Append the current date and time to the beginning of a new file
File.AppendAllText(trgd, DateTime.UtcNow.ToString("G") + Environment.NewLine);
        while (!TrueRandom.RandInternet.IsAvailableUniform())
        {
        print("Waiting for True RNG/Random.org data...");
        } //End while loop
            for (int i = 0; i < 10; i++)
            {   
                double rn = TrueRandom.RandInternet.Uniform();
                //Append all the Random.org-pulled data to a single String
                sb.AppendLine(rn.ToString());
            } //End for writing loop
        //Write the "truly" random String to a file
        File.WriteAllText(trgd, sb.ToString());
        } //End date check if
    } //End Start
    // Update is called once per frame
    void Update () {
        TS.Translate(Vector3.right * Input.GetAxis("Horizontal") * pspeed * Time.deltaTime);
        if (TS.position.x>11.25f || TS.position.x<-11.25f) {
            TS.position = new Vector3 (TS.position.x*-1, TS.position.y, TS.position.z);
        }
        //Fire a laser with the Spacebar.
        if (Input.GetKeyDown("space")) {

            //Get pseudo-randomized laser position
            //This works but is not "truly" random. The random data should be pulled from the trgd file
            //float laspo = TrueRandom.RandInternet.Uniform() > 0.5f ? -1.917277f : 1.917277f;
            //Set Laser position
            Vector3 position = new Vector3(TS.position.x/*+laspo*/, TS.position.y+3.50f, TS.position.z);
            //Fire projectile.
            Instantiate(Resources.Load("LaserFab"), position, Quaternion.identity);
        }
        if (Time.time - timer > 0.4f) {
            renderer.enabled = true;
        }
        print ("Lives remaining: " + playerLives + " Score: " + score + " Current playing time: " + "0");
    }
    void OnTriggerEnter(Collider collider)
    {
        if (collider.CompareTag ("Enemy")) { //Tag is name of prefab.
            //When the enemy hits the player, destroy the player and the enemy.
            playerLives--;
            renderer.enabled = false;
            timer = Time.time;
        }
        if (playerLives < 1)
            Destroy(this.gameObject);
    }
}

检查文件的存在和修改日期

您可以创建一个FileInfo对象,并从中获取所有信息:

var f = new FileInfo(@"R:'trrnd.txt");
if(!f.Exists || f.CreationTime < DateTime.Now.AddDays(-1))
{
    //do stuff
}

您也可以使用UTC次:

if(!f.Exists || f.CreationTimeUtc < DateTime.UtcNow.AddDays(-1))
{
    //do stuff
}

你可以尝试这样的东西:

if (!File.Exists(@"C:'file.txt") || 
        (File.GetCreationTime(@"C:'file.txt") < DateTime.Now.AddDays(-1)))
{
    //Recreate file
}
string trgd = "D:''trrnd.txt";
if(File.Exists(trgd))
{
    var dt = File.GetCreationTimeUtc(trgd);
    if((dt - DateTime.UtcNow).Hour > 24)
    {
        //Overwrite existing file
        File.WriteAllLines(trgd,"Some new text");
    }
}
else
{
    //append to existing file
    File.AppendAllText(trgd,"Some Text");
}