Seba Plawner
Seba Plawner

Reputation: 1

Way of hiding important XML files using C# XNA

I'm developing a game using XNA and I'm storing all my data like dialogs, texts and user preferences in a XML file but I wonder how I could hide all that data to not be changed by those who may open the folder where I'm storing my files. Thanks

Upvotes: 0

Views: 145

Answers (1)

Darek
Darek

Reputation: 4797

Sample extension class to compress/decompress XML documents

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);
            }
        }
    }
}

Sample use:

    static void Main(string[] args)
    {
        var doc = new XDocument(
            new XElement("Root", new XElement("Item1")));
        doc.Compress("test1");

        var doc2 = Extensions.Decompress("test1");
    }

Upvotes: 2

Related Questions