这是一个使用MemoryStream
使用 MemoryStream 将 XML 数据保存到 base64 编码数据并将其写入文件。
using (var ms = new MemoryStream())
{
// Memory Stream
using (XmlWriter writer = XmlWriter.Create(ms,settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("Database");
writer.WriteStartElement("Entry");
writer.WriteAttributeString("key", "value");
writer.WriteEndElement();
writer.WriteEndElement();
writer.Flush();
writer.Close();
// XML Data (Debug)
Console.WriteLine(new UTF8Encoding().GetString(ms.ToArray()));
// Pre encoding hex (Debug)
Console.WriteLine(BitConverter.ToString(ms.ToArray()));
string s = Convert.ToBase64String(ms.ToArray());
Console.WriteLine(s); // (Debug)
// Post encoding
File.WriteAllText(@"C:\Temp\A.enc", s);
}
}
回读文件
// Read encoded file back to xml
string enc_text = File.ReadAllText(@"C:\Temp\A.enc");
Console.WriteLine(enc_text); // (Debug)
// Pre encoding hex
byte[] mem_bytes = Convert.FromBase64String(enc_text);
Console.WriteLine(BitConverter.ToString(mem_bytes)); // (Debug)
// XML Data
Console.WriteLine(new UTF8Encoding().GetString(mem_bytes));
// Read byte array into Reader
using (var stream = new MemoryStream(mem_bytes))
{
using (XmlReader reader = XmlReader.Create(stream))
{
// Use reader as desired
}
}