這是不是一個非常有效的解決方案,因爲插入(它可能會更好地構建字符串,從編碼的文件內容中添加76個字符,然後一個新行,然後是76個字符,然後又是一個新的行,...),但它很短並顯示出總體思路。如果需要考慮內存使用情況和性能,還可以考慮用直接將字節編碼爲StringBuilder
的代碼替換Convert.ToBase64String()
調用。
public static XElement BuildNode(Byte[] data, XName tagName, Int32 lineLength)
{
StringBuilder sb = new StringBuilder(Convert.ToBase64String(data));
Int32 position = 0;
while (position < sb.Length)
{
sb.Insert(position, Environment.NewLine);
position += lineLength + Environment.NewLine.Length;
}
sb.AppendLine();
return new XElement(tagName, sb.ToString());
}
例如
String text = "I have got to convert a PDF to a Base64 Encoded " +
"and write it to a element in a XML file.";
Byte[] data = Encoding.UTF8.GetBytes(text);
StringBuilder sb = new StringBuilder();
TextWriter tw = new StringWriter(sb);
using (var writer = new XmlTextWriter(tw) { Formatting = Formatting.Indented })
{
XDocument document = new XDocument(BuildNode(data, "Content", 40));
document.Save(writer);
}
Console.WriteLine(sb.ToString());
打印以下。
<?xml version="1.0" encoding="utf-16"?>
<Content>
SSBoYXZlIGdvdCB0byBjb252ZXJ0IGEgUERGIHRv
IGEgQmFzZTY0IEVuY29kZWQgYW5kIHdyaXRlIGl0
IHRvIGEgZWxlbWVudCBpbiBhIFhNTCBmaWxlLg==
</Content>