开发unity的过程中有不断进行沙盒读取操作,每次操作都需要进行一堆代码书写,并且容易暴露数据,在这里进行封装一个类进行方便沙盒读写和进行加密
直接贴代码
/// <summary>
/// ***作者:黛墨***
///*** 时间:2018-9-16***
/// *** XmlManage***
/// </summary>
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using UnityEngine;
using System.Text;
using System.Security.Cryptography;
using System;
public class XmlManage {
private string Path=null;
public XmlNode Root = null;
private XmlDocument Doc = null;
public bool Encryption = false;//是否采用加密方式进行保存
public string Key="123456789";//必须32位不是32位进行补充32位
private bool isone = false;
public XmlManage(string path,string key=null)
{
#if UNITY_EDITOR||UNITY_STANDALONE_WIN||UNITY_IPHONE
Path = Application.persistentDataPath + @"/";
#elif UNITY_ANDROID
Path = "file://" + Application.persistentDataPath+ @"/";
#endif
this.Path += path+".xml";
//查找目录
int index = this.Path.Length - 1;
for (int i = this.Path.Length-1; i >=0; i--)
{
if (this.Path[i] == '/' || this.Path[i] == '\\')
{
index = i;
break;
}
}
StringBuilder pathstr = new StringBuilder();
for (int i = 0; i <=index; i++)
{
pathstr.Append(this.Path[i]);
}
if (!Directory.Exists(pathstr.ToString()))
{
Directory.CreateDirectory(pathstr.ToString());
}
if (key != null) { Encryption = true;Key = key; }
if (Encryption)
{
if (Key.Length < 32)
{
index = 0;
while (Key.Length < 32)
{
Key += Key[index];
index++;
}
}
else
{
if (Key.Length > 32)
{
StringBuilder str_ = new StringBuilder();
for (int i = 0; i < 32; i++)
{
str_.Append(key[i]);
}
Key = str_.ToString();
}
}
}
Read();
}
public void Read()
{
XmlDocument doc = new XmlDocument();
if (!File.Exists(Path))
{
XmlElement newxmlele = doc.CreateElement("Root");
XmlAttribute xmlattri = doc.CreateAttribute("Type");
xmlattri.Value = "root";
newxmlele.SetAttributeNode(xmlattri);
Root = newxmlele;
doc.AppendChild(Root);
Doc = doc;
Sava();
isone = true;
}
else
{
//如果采样加密方式进行其他方式读取
if (Encryption)
{
doc.LoadXml(Decrypt(File.ReadAllText(Path)));
}
else
doc.Load(Path);
Root = doc.SelectSingleNode("Root");
}
Doc = doc;
}
public bool IsCreate { get { return isone; } }
public int GetInt(string name)
{
var node=GetNode(name);
if (node == null) return 0;
var type=node.Attributes["Type"];
if (type == null) return 0;
if (type.Value == "Int")
return int.Parse(node.InnerText);
else return 0;
}
public void SetInt(string name,int value)
{
var node = GetNode(name);
if (node == null)
{
var ele = Doc.CreateElement(name);
ele.InnerText = value.ToString();
var att = Doc.CreateAttribute("Type");
att.Value = "Int"; ele.SetAttributeNode(att);
Root.AppendChild(ele);
}
else
if(node.Attributes[0].Value=="Int")
node.InnerText = value.ToString();
}
public float GetFloat(string name)
{
var node = GetNode(name);
if (node == null) return 0;
var type = node.Attributes["Type"];
if (type == null) return 0;
if (type.Value == "Float")
return float.Parse(node.InnerText);
else return 0;
}
public void SetFloat(string name, float value)
{
var node = GetNode(name);
if (node == null)
{
var ele = Doc.CreateElement(name);
ele.InnerText = value.ToString("F5");
var att = Doc.CreateAttribute("Type");
att.Value = "Float"; ele.SetAttributeNode(att);
Root.AppendChild(ele);
}
else
if (node.Attributes[0].Value == "Float")
node.InnerText = value.ToString("F5");
}
public bool GetBool(string name)
{
var node = GetNode(name);
if (node == null) return false;
var type = node.Attributes["Type"];
if (type == null) return false;
if (type.Value == "Bool")
return bool.Parse(node.InnerText);
else return false;
}
public void SetBool(string name, bool value)
{
var node = GetNode(name);
if (node == null)
{
var ele = Doc.CreateElement(name);
ele.InnerText = value.ToString();
var att = Doc.CreateAttribute("Type");
att.Value = "Bool"; ele.SetAttributeNode(att);
Root.AppendChild(ele);
}
else
if (node.Attributes[0].Value == "Bool")
node.InnerText = value.ToString();
}
public bool Exists(string name)
{
return Root.SelectNodes(name).Count > 0?true:false;
}
public XmlNode GetNode(string name)
{
var arr = Root.SelectNodes(name);
return arr.Count > 0 ? arr[0] : null;
}
public void Sava()
{
//Debug.Log(ConvertXmlToString(Doc));
if (Encryption)
{
string str = ConvertXmlToString(Doc);
File.WriteAllText(Path, Encrypt(str));
}
else
Doc.Save(Path);
}
public override string ToString()
{
return "XmlManage:"+ Path+Root.ToString()+":"+ ConvertXmlToString(Doc);
}
public void Delate()
{
if (File.Exists(Path))
{
File.Delete(Path);
}
}
private string Encrypt(string toE)//加密
{
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(Key);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.ECB;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toE);
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
private string Decrypt(string toD)//解密
{
//加密和解密采用相同的key,具体值自己填,但是必须为32位//
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(Key);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.ECB;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] toEncryptArray=null;
byte[] resultArray=null;
try
{
toEncryptArray = Convert.FromBase64String(toD);
resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
}
catch (Exception)
{
throw new Exception("解密失败核对密码");
}
return UTF8Encoding.UTF8.GetString(resultArray);
}
public string ConvertXmlToString(XmlDocument xmlDoc)
{
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, null);
writer.Formatting = Formatting.Indented;
xmlDoc.Save(writer);
StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8);
stream.Position = 0;
string xmlString = sr.ReadToEnd();
sr.Close();
stream.Close();
return xmlString;
}
}
以上代码不进行阐述我接下来贴出使用方法和效果