How to hide XML files content

♀尐吖头ヾ 提交于 2019-12-11 06:26:10

问题


I have a series of XML files which I want to hide from the client and I want to be available only for the application. I read and write from/to them using XmlSerializer. How can this be done? I read about embedded resources, but from what I've seen, I need to read and write to the files using some sort of stream. I was wondering if there is another approach which would allow me to access them using XmlSerializer and hide them from the client.


回答1:


If you just want to hide them (kind of obfuscation to prevent casual changes) you may consider to compress them. For example this an example of C# deserialization function:

static T Deserialize<T>(string path, object obj)
{
    var serializer = new XmlSerializer(typeof(T));

    using (var stream = new GZipStream(File.OpenRead(path),
                                       CompressionMode.Decompress))
    {
        return (T)serializer.Deserialize(stream);
    }
}

Your customers will see a binary file and they won't be able to change/inspect it (moreover it's just a compressed stream so they can't even unzip them). For clarity this is equivalent serialization function:

static void Serialize<T>(string path, T obj)
{
    var serializer = new XmlSerializer(typeof(T));

    using (var stream = new GZipStream(File.Create(path),
                                       CompressionMode.Compress))
    {
        serializer.Serialize(stream, obj);
    }
}

Note: in your original question you didn't say anything about your environment (.NET? Java?), I provided code assuming you're programming in C# but you can apply same technique with any other language/environment you're using.

Update this is a small test program to see how it works:

public class Test
{
    public string Name { get; set; }
    public string Value { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Serialize(@"c:\test.dat", new Test { Name = "A", Value = "B" });
    }

    // Place here Serialization<T>() method
}


来源:https://stackoverflow.com/questions/20657144/how-to-hide-xml-files-content

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!