XML 為純文字格式,無法直接儲存二進位資料。解決方案:將圖片讀取為位元組陣列 → **Base64 編碼** → 寫入 XML 文字節點。.NET 提供 `XmlTextWriter.WriteBase64` 直接支援串流式編碼寫入,避免大圖載入記憶體。
public void SaveImageToXml(string imagePath, string xmlPath)
{
const int BufferSize = 8192; // 8KB 緩衝區
byte[] buffer = new byte[BufferSize];
int bytesRead;
using (FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
using (BinaryReader br = new BinaryReader(fs))
using (XmlTextWriter xw = new XmlTextWriter(xmlPath, Encoding.UTF8))
{
xw.Formatting = Formatting.Indented;
xw.WriteStartDocument();
xw.WriteStartElement("picture", "ContactDetails", "https://example.com/ns");
xw.WriteStartElement("image");
xw.WriteAttributeString("imageName", Path.GetFileName(imagePath));
xw.WriteAttributeString("contentType", GetMimeType(imagePath));
xw.WriteAttributeString("length", fs.Length.ToString());
// 串流式 Base64 編碼寫入
while ((bytesRead = br.Read(buffer, 0, BufferSize)) > 0)
{
xw.WriteBase64(buffer, 0, bytesRead);
}
xw.WriteEndElement(); // image
xw.WriteEndElement(); // picture
xw.WriteEndDocument();
}
}
private string GetMimeType(string path)
{
var ext = Path.GetExtension(path).ToLowerInvariant();
return ext switch
{
".jpg" or ".jpeg" => "image/jpeg",
".png" => "image/png",
".gif" => "image/gif",
".bmp" => "image/bmp",
_ => "application/octet-stream"
};
}
public void RestoreImageFromXml(string xmlPath, string outputDir)
{
using (XmlTextReader xr = new XmlTextReader(xmlPath))
{
xr.MoveToContent();
string fileName = xr.GetAttribute("imageName");
string contentType = xr.GetAttribute("contentType");
long length = long.Parse(xr.GetAttribute("length"));
xr.ReadStartElement("image"); // 定位到 Base64 內容
string outputPath = Path.Combine(outputDir, fileName);
using (FileStream fs = new FileStream(outputPath, FileMode.Create))
{
byte[] buffer = new byte[8192];
int decoded;
// XmlTextReader 內建 Base64 解碼
while ((decoded = xr.ReadContentAsBase64(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, decoded);
}
}
}
}
掌握 `XmlTextWriter.WriteBase64` 串流式編碼技巧,即可優雅處理「XML 承載二進位資料」的需求,兼顧記憶體效率與程式碼簡潔性。