Search Unity

Is it safe to replace files with File.Create?

Discussion in 'Scripting' started by Sendatsu_Yoshimitsu, Aug 8, 2018.

  1. Sendatsu_Yoshimitsu

    Sendatsu_Yoshimitsu

    Joined:
    May 19, 2014
    Posts:
    691
    My narrative workflow involves assembling quests out of scriptableobjects, then running a function in edit mode that finds every relevant SO, assembles the final quests, and serializes them into the JSON files that the game actually uses to store quests. The actual read/write function is super-simple:

    Code (CSharp):
    1.  
    2.        string path;
    3.        string serializedFile; //both variables set elsewhere in code
    4.        FileStream jsonFile = File.Create(path);
    5.        StreamWriter writer = new StreamWriter(jsonFile);
    6.        writer.Write(serializedFile);
    7.        writer.Close();
    As a pleasant side-effect, I noticed that if I already have a JSON file with the name and path that I'm writing too, it gets overwritten. This wasn't intended, but it's appreciated since I don't have to manually futz with the data. However, it occurs to me to wonder: is there any downside to explicitly using File.Create to delete outdated versions of the files? Or is this A-OK as-written?
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,531
    The documentation:
    https://msdn.microsoft.com/en-us/library/d62kzs03(v=vs.110).aspx

    Note there are overloads with more options:
    https://msdn.microsoft.com/en-us/library/system.io.file.create(v=vs.110).aspx

    As the documentation for that one says:
    If your anticipated behaviour is that it creates a file if none exists, or overwrites the file if one does exist... welp, then it does what you want it to do.

    The only stipulation I could think of is the permissions of the file. It could fail if the file can't be overwrittten. This may occur if the file is owned by someone else, or if the file is currently locked by another process. It's usually best to wrap file access code with a try/catch so as to deal with those situations.
    (see the exceptions section of the documentation I linked to see what may go wrong)
     
  3. Sendatsu_Yoshimitsu

    Sendatsu_Yoshimitsu

    Joined:
    May 19, 2014
    Posts:
    691
    Oh, I didn't know it was a .NET thing, for some reason I'd assumed it was a Unity internal method... thanks for the documentation! I'll probably wrap it with try/gets later today, it's incredibly schlocky but as a quick & dirty editor tool it seems to do the job. Thanks for the clarification! :)