我正在使用XNA开发游戏,我将所有数据(如对话框,文本和用户首选项)存储在XML文件中,但我想知道如何隐藏所有数据,以免被那些可能打开的人更改我存储文件的文件夹。感谢
答案 0 :(得分:2)
压缩/解压缩XML文档的示例扩展类
public static class Extensions
{
public static void Compress(this XDocument doc, string name)
{
byte[] buffer = Encoding.UTF8.GetBytes(doc.ToString(SaveOptions.DisableFormatting));
using (var ms = new MemoryStream(buffer.Length))
{
ms.Write(buffer,0,buffer.Length);
ms.Seek(0, SeekOrigin.Begin);
using (var fs = new FileStream(name, FileMode.Create))
{
using (var gzipStream = new GZipStream(fs, CompressionMode.Compress))
{
ms.CopyTo(gzipStream);
}
}
}
}
public static XDocument Decompress(string name)
{
using (var fs = new FileStream(name,FileMode.Open))
{
using (var ms = new MemoryStream())
{
using (var gzip = new GZipStream(fs,CompressionMode.Decompress))
{
gzip.CopyTo(ms);
}
ms.Seek(0, SeekOrigin.Begin);
string s = Encoding.UTF8.GetString(ms.ToArray());
return XDocument.Parse(s);
}
}
}
}
样品使用:
static void Main(string[] args)
{
var doc = new XDocument(
new XElement("Root", new XElement("Item1")));
doc.Compress("test1");
var doc2 = Extensions.Decompress("test1");
}