This might be a strange question but is there a way to save a file in
a XML file?
Something similar to saving a Blob in a SQL Database.
Is this possible with C#?
I would like in the future to get data from a SQL table where on of
the columns holds a Blob.
I wonder if I could save that Blob on a XML file ... And if in the
future I can get the file for download.
As David says, you can use a character-based encoding for binary data,
such as Base64, to store binary data in your XML.
In fact, here are a couple of extension methods I wrote a while back to do
just that:
public static XCData ToXmlCData(this byte[] rgb)
{
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = new XmlTextWriter(new
StringWriter(sb)))
{
writer.WriteBase64(rgb, 0, rgb.Length);
}
return new XCData(sb.ToString());
}
public static byte[] FromXmlCData(this XElement xcdata)
{
using (MemoryStream streamOut = new MemoryStream())
using (XmlReader reader = new XmlTextReader(new
StringReader(xcdata.ToString())))
{
byte[] rgb = new byte[4096];
int cb;
reader.MoveToContent();
while ((cb = reader.ReadElementContentAsBase64(rgb, 0,
rgb.Length)) > 0)
{
streamOut.Write(rgb, 0, cb);
}
return streamOut.ToArray();
}
}
Unfortunately, that's the best I could come up with. My main issues are
that I had to use the older System.Xml Base64 support because
System.Xml.Linq doesn't include it, and the only way I saw to convert from
Base64 back to binary easily was to convert the entire node to a string
and read the string (which IMHO is a problem because there's already a
perfectly good string attached to the XElement object containing the data
you want to read, but the .NET Base64 support doesn't know what to do with
a raw string like that).
You can address those problems reasonably easily by using a third-party
Base64 implementation, or writing your own. But I wanted to see if I
could get a "pure .NET" solution. Turns out, I could, even if it is a
little awkward.
For relatively small sizes of data, I think it should work just fine
though. You probably don't want to be embedding hundreds or thousands of
megabytes into your XML file anyway. Base64 will inflate your data some
20-30%, which is fine for small chunks of data but can get to be a real
performance and disk space problem for very large data.
Pete