Monday, March 2, 2015

Helper for FileOperations on Windows Phone and Windows 8 in Unity3d

Standard
Hello All:

Unity3d is supporting both Windows Phone and Windows 8-8.1. However there are some points which needs to be taken care of when porting our games to Windows Phone and Windows 8-8.1. One such point is support of File operations.

Basic File related operations comes from File (System.IO) class. But this class is not supported for Windows Phone. Unity3d has provided UnityEngine.Windows to provide File handling functions on Windows Phone and Windows 8.

Below is a helper class which wraps both UnityEngine.Windows and System.IO and provides a uniform access to file operations.

using System;
using System.Text;
#if UNITY_WINRT
using UnityEngine.Windows;
#else
using System.IO;
#endif

namespace Common.IO
{
    public class FileHandle
    {

        public static bool Exists(string path)
        {
            return File.Exists(path);
        }

        public static string ReadAllText(string path)
        {
#if UNITY_WINRT
            var data = ReadAllBytes(path);
            return Encoding.UTF8.GetString(data,0,data.Count());
#else
            return File.ReadAllText(path);
#endif
        }

        public static byte[] ReadAllBytes(string path)
        {
            return File.ReadAllBytes(path);
        }

        public static void WriteAllBytes(string path, byte[] data)
        {
            File.WriteAllBytes(path, data);
        }

        public static void WriteAllText(string path, string data)
        {
#if UNITY_WINRT
            WriteAllBytes(path, Encoding.UTF8.GetBytes(data));
#else
            File.WriteAllText(path, data);
#endif
        }

        public static void Delete(string path)
        {
            File.Delete(path);
        }
    }
}

Do let me know if this helps. Happy coding :)
Thanks for printing this post. Hope you liked it.
Keep visiting and sharing.
Thanks,
Ashwani.

3 comments :

  1. there's a error in line 23 which says Argument `#3' cannot convert `object' expression to type `int' can you please resolve it thnx.

    ReplyDelete
  2. Hello Raj:
    Thanks for the comment. However the code you pointed to is correct. You can refer these links: http://forum.unity3d.com/threads/system-text-encoding-utf8-getstring-byte-error.203175/ and https://msdn.microsoft.com/library/windows/apps/05cts4c3%28v=vs.105%29.aspx.

    ReplyDelete
  3. Hello!
    Thanks for the useful information)
    Very interesting, I want to try to use this resource.
    Richard Brown online data room

    ReplyDelete