Skip to content

Instantly share code, notes, and snippets.

@fumobox
Last active August 29, 2015 14:07
Show Gist options
  • Save fumobox/a60b7c4b2367d083ae3f to your computer and use it in GitHub Desktop.
Save fumobox/a60b7c4b2367d083ae3f to your computer and use it in GitHub Desktop.
XPref.cs
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