HoloLens and Unity tip #004 – Storing and retrieving data on HoloLens device storage
storage box storing spaces in garage lockers units or container with room and space for renting

HoloLens and Unity tip #004 – Storing and retrieving data on HoloLens device storage

There are different ways of storing data on HoloLens device storage. One of my favorite is using the persistent data path which allows you to store data which need to be kept between runs of your application. This path allows you to perform read and write actions without any (strange) capabilities activated and can be used in Windows Store apps.

The best way is using the public static property called Application.persistentDataPath from Unity. This will give per type of device a specific path back where the data can be stored.

Some sample code below shows you how to store and retrieve some type of custom object by converting it to and from json from the device storage.

        public MyObject ReadData(string filename)
        {
            string path = string.Format("{0}/mydata/{1}.json", Application.persistentDataPath, filename);

            byte[] data = UnityEngine.Windows.File.ReadAllBytes(path);
            string json = Encoding.ASCII.GetString(data);

            MyObject obj= JsonConvert.DeserializeObject(json);

            return obj;
        }

        public void SaveData(string filename, MyObject obj)
        {
            string path = string.Format("{0}/mydata/{1}.json", Application.persistentDataPath, filename);

            string json = JsonConvert.SerializeObject(obj);
            byte[] data = Encoding.ASCII.GetBytes(json);

            UnityEngine.Windows.File.WriteAllBytes(path, data);
        }

The methods which are used can be found in the UnityEngine.Windows.File class. If the file already exists it is overwritten by your new file.

It is even possible to have some control over directories by using the UnityEngine.Windows.Directory class.  There is not really a methods to get all the files from some directory. In that case you need to build something yourself. For example a known file at a specific location containing references to other files.

Important to remember the following;

  1. The data is removed/ cleared as soon as you remove the app or redeploy the app via a package or Visual Studio.
  2. The data will persist when you are doing debug sessions via Visual Studio and during debug you deploy new or updated code.

Another fun thing is that you can view and access the data through the File Explorer in the Windows Device Portal.

LocalStateFolder

Watch out. These folders can only be reached through the Windows Device Portal. They are (with the current build of today) not available via the file explorer on your computer when the HoloLens device is connected through the cable.

Leave a Reply