Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write XML in Base64 encoding

Tags:

c#

.net

xml

base64

Following my questions about storing data, it has been suggested that I could use XML but then obfuscate the file by encoding it using Base64. I like this idea, and I have achieved what I want in XML, but I don't know how to save it in Base64. This is my code so far:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

XmlWriter write = XmlWriter.Create("C:\\Users\\Andy\\Desktop\\database.xml", settings);
write.WriteStartDocument();
write.WriteStartElement("Database");
write.WriteStartElement("Entry");
write.WriteAttributeString("key", "value");
write.WriteEndElement();
write.WriteEndElement();

write.Flush();
write.Close();
like image 707
Andy Avatar asked Jul 24 '13 13:07

Andy


1 Answers

Write it:

var sb = new StringBuilder(); 
var settings = new XmlWriterSettings();
//..settings
using (var writer = XmlWriter.Create(sb, settings))
{
    //...
}
//http://stackoverflow.com/questions/1564718/using-stringwriter-for-xml-serialization
var encoding = new UnicodeEncoding(); 
string s = Convert.ToBase64String(encoding.GetBytes(sb.ToString()));

File.WriteAllText("c:\temp.txt", s);

Read it:

string readText = File.ReadAllText("c:\temp.txt");
byte[] toDecodeByte = Convert.FromBase64String(readText);

using (var stream = new MemoryStream(toDecodeByte))
{
    using (XmlReader reader = XmlReader.Create(stream))
    {
        //.. read your xml
    }
}
like image 180
giammin Avatar answered Sep 28 '22 03:09

giammin