Exemplo n.º 1
0
 public static int Save(object data, string name, FileType type)
 {
     try
     {
         using (FileStream fs = File.Open(GetPath(type) + "/" + name + GetExt(type), FileMode.OpenOrCreate))
         {
             AmberBinaryFormatter bf = new AmberBinaryFormatter();
             bf.Serialize(fs, data);
             fs.Close();
         }
         return(1);
     }
     catch (Exception ex)
     {
         Debug.LogError("unable to save file\n" + ex);
         return(-1);
     }
 }
Exemplo n.º 2
0
    public bool Save(string path, string filename, string extension)
    {
        // check if class type is marked as serializable
        Type type = GetType();

        if (!type.IsDefined(typeof(SerializableAttribute), false))
        {
            throw new InvalidOperationException("Tried saving class of type " + type.ToString() + ", but it was not marked as Serializable");
        }


        var bindingFlags =
            BindingFlags.Instance |
            BindingFlags.NonPublic |
            BindingFlags.Public;

        List <object> fieldValues = GetType()
                                    .GetFields(bindingFlags)
                                    .Select(field => field.GetValue(this))
                                    .ToList();

        List <string> fieldNames = GetType()
                                   .GetFields(bindingFlags)
                                   .Select(field => field.Name)
                                   .ToList();

        string log = "SAVING TYPE '" + GetType() + "' - it has " + fieldValues.Count + " fields\n";

        for (int i = 0; i < fieldValues.Count; i++)
        {
            Type fieldType       = fieldValues[i].GetType();
            bool shouldSaveAsRef = ShouldSaveAsGuidRef(fieldType);

            log += "field " + (i + 1) + ": " + fieldNames[i]
                   + " [" + fieldType.ToString() + "] => '"
                   + fieldValues[i].ToString() + "'"
                   + (shouldSaveAsRef  ? "   << WILL BE CONVERTED TO GUID REFERENCE >>" : "")
                   + "\n";
        }

        Debug.Log(log);

        // TODO: Find out if current class is Serializable!

        // BINARY FORMATTING TO FILE
        try
        {
            AmberBinaryFormatter binaryFormatter = new AmberBinaryFormatter();
            string fullPath = Application.persistentDataPath + "/" + filename + extension;

            using (FileStream fileStream = File.Open(fullPath, FileMode.OpenOrCreate))
            {
                binaryFormatter.Serialize(fileStream, this);
                fileStream.Close();
            }

            Debug.Log("Saved file to " + fullPath);
            return(true);
        }
        catch (Exception ex)
        {
            Debug.LogError("FAILED SAVING FILE\n" + ex);
            return(false);
        }
    }