Skip to content

IDataStorage Interface

wvdvegt edited this page Jan 10, 2018 · 2 revisions

IDataStorage

An IDataStorage interface can be implemented in C# like:

/// <summary>
/// Exists the given file.
/// </summary>
///
/// <param name="fileId"> The file identifier to delete. </param>
///
/// <returns>
/// true if it succeeds, false if it fails.
/// </returns>
public bool Exists(string fileId)
{
    return File.Exists(Path.Combine(StorageDir, fileId));
}

/// <summary>
/// Gets the files.
/// </summary>
///
/// <returns>
/// A List&lt;String&gt;
/// </returns>
public String[] Files()
{
    return Directory.GetFiles(StorageDir).ToList().ConvertAll(
new Converter<String, String>(p => p.Replace(StorageDir + Path.DirectorySeparatorChar, ""))).ToArray();

    //! EnumerateFiles not supported in Unity3D.
    //
    //return Directory.EnumerateFiles(StorageDir).ToList().ConvertAll(
    //    new Converter<String, String>(p => p.Replace(StorageDir +  Path.DirectorySeparatorChar, ""))).ToList();
}

/// <summary>
/// Saves the given file.
/// </summary>
///
/// <param name="fileId">   The file identifier to delete. </param>
/// <param name="fileData"> Information describing the file. </param>
public void Save(string fileId, string fileData)
{
    File.WriteAllText(Path.Combine(StorageDir, fileId), fileData);
}

/// <summary>
/// Loads the given file.
/// </summary>
///
/// <param name="fileId"> The file identifier to delete. </param>
///
/// <returns>
/// A String.
/// </returns>
public string Load(string fileId)
{
    return File.ReadAllText(Path.Combine(StorageDir, fileId));
}

/// <summary>
/// Deletes the given fileId.
/// </summary>
///
/// <param name="fileId"> The file identifier to delete. </param>
///
/// <returns>
/// true if it succeeds, false if it fails.
/// </returns>
public bool Delete(string fileId)
{
    if (Exists(fileId))
    {
	File.Delete(Path.Combine(StorageDir, fileId));

	return true;
    }

    return false;
}
  • In Files() there where some Linq related issues with respect to Unity3D. The original api returned EnumerateFiles and returned a List. Both where having issues on Unity3D.
  • The code expects a field StorageDir to be defined (R/W) and the directory to be present. This could be done in the Bridge constructor.
  • The StorageDir is development and (mobile) target platform dependent.
  • An in memory storage could simply be mapped on a Dictionary<String,String> where keys are the fileId's and values the files content.
  • Files should either be text or be (base64) encoded as text.
  • This interface should be used for all local storage of data.

Clone this wiki locally