Last active
August 29, 2015 14:07
-
-
Save fumobox/a60b7c4b2367d083ae3f to your computer and use it in GitHub Desktop.
XPref.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Xml; | |
using System.Xml.Serialization; | |
using System.IO; | |
using System.Security.Cryptography; | |
public class XPref { | |
static readonly DESCryptoServiceProvider _provider; | |
static XPref() { | |
_provider = new DESCryptoServiceProvider(); | |
} | |
public static void Save(string path, object obj, bool encrypt = true) { | |
var p = Path.Combine(Application.persistentDataPath, path); | |
if (encrypt) { | |
using (var fs = new FileStream(p, FileMode.Create)) { | |
using (var cs = new CryptoStream(fs, _provider.CreateEncryptor(), CryptoStreamMode.Write)) { | |
var serializer = new XmlSerializer(obj.GetType()); | |
serializer.Serialize(cs, obj); | |
} | |
} | |
} else { | |
using (var fs = new FileStream(p, FileMode.Create)) { | |
var serializer = new XmlSerializer(obj.GetType()); | |
serializer.Serialize(fs, obj); | |
} | |
} | |
} | |
public static T Load<T>(string path, bool decrypt = true) { | |
var p = Path.Combine(Application.persistentDataPath, path); | |
if (!File.Exists(p)) { | |
return default(T); | |
} | |
if (decrypt) { | |
using (FileStream fs = File.Open(p, FileMode.Open)) { | |
using (CryptoStream cs = new CryptoStream(fs, _provider.CreateDecryptor(), CryptoStreamMode.Read)) { | |
XmlSerializer xmlser = new XmlSerializer(typeof(T)); | |
return (T)xmlser.Deserialize(cs); | |
} | |
} | |
} else { | |
using (FileStream fs = File.Open(p, FileMode.Open)) { | |
XmlSerializer xmlser = new XmlSerializer(typeof(T)); | |
return (T)xmlser.Deserialize(fs); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment