2021年4月5日星期一

How to check if there is enough memory available on disk before attempting to save, with binaryformatter filestream?

With Unity C#, is there a way to check to see if there is enough disk space before trying to save to disk? I have not been able to figure this out.

The problem that I am having is that if the disk is full, then the game save cannot be saved to disk and the user will lose all of their data because the save attempt will overwrite the existing file.

Currently, the best I have figured out is to before I attempt the save, to load the most recent save, and if an error is thrown when the save is attempted, then I simply write the most recent save (that I know fit on the disk before) back to the disk.

The problem is that I am not sure that this works 100% of the time and I would like to know if there is a better way.

Current code:

public static void SaveToFile(this object obj, string saveName)  {      string savePath = FilePath(saveName);        object oldFile = LoadFromFilePath(savePath);        try      {          obj.SaveToPath(savePath);      }      catch      {          oldFile.SaveToPath(savePath);            throw; // tell user that file could not be saved due to out of disk space      }  }    private static string FilePath(string saveName)  {      return Path.Combine(Application.persistentDataPath, saveName);  }    private static void SaveToPath(this object obj, string savePath)  {      FileStream file = File.Create(savePath);        BinaryFormatter bf = new BinaryFormatter();        try      {          bf.Serialize(file, obj);      }      catch      {          throw;      }      finally      {          file.Close();      }  }  
https://stackoverflow.com/questions/66945287/how-to-check-if-there-is-enough-memory-available-on-disk-before-attempting-to-sa April 05, 2021 at 03:49AM

没有评论:

发表评论