简体   繁体   中英

Check both existence and modified date of file

I'm creating a script that uses data pulled from Random.org. I'm having trouble figuring out how to make it work without repeating the file-creation part of the script. What I'm looking to do is create a new file if the file does not exist or if the file is >24 hours old.

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);
    }
}

You can create a FileInfo object and get all this information from that as well:

var f = new FileInfo(@"R:\trrnd.txt");

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

You can also use UTC times:

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

You can try something like that:

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM