要在多層架構中傳送二進位文件(.doc、.xls、.ppt),最通用的做法是先轉成 Base64 字串包進 XML,再讓 XML 走 Web Service、.NET Remoting 或一般 HTTP 通道。XML 的平台中立性意味著服務端可以是 .NET,客戶端也可以是 Java——雙方只需要對文件格式有共識。以下範例示範雙向轉換。
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Xml;
namespace MyWindows
{
/// <summary>
/// 這個範例示範如何把 Office 文件編碼為 XML 文件,
/// 以及如何把生成的 XML 文件轉換回 Office 文件。
///
/// 轉成 XML 之後,就可以用 Web Service、.NET Remoting、WinSock
/// 等機制傳送。XML 解決了多層架構中的資料傳輸問題:例如客戶端
/// 透過 Web Service 取得服務端的 Office 文件,修改後再回傳。
///
/// 若整體方案跨平台,節點之間的互動盡量避免 RPC,改用基於文件的
/// 交換方式(例如 .NET 的 MSMQ、J2EE 的 JMQ)會更穩健。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// 四個 Button、一組開啟與存檔對話框,以及兩個 XMLDocument
/// </summary>
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Xml.XmlDocument mXmlDoc;
private System.Xml.XmlDocument doc;
private System.ComponentModel.Container components = null;
public Form1()
{
// Windows 表單設計工具所需要
InitializeComponent();
}
/// <summary>
/// 清理所有正在使用的資源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if( components != null )
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows 表單設計工具產生的程式碼
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.SuspendLayout();
// button1
this.button1.Location = new System.Drawing.Point(96, 32);
this.button1.Name = "button1";
this.button1.TabIndex = 0;
this.button1.Text = "生成 XML";
this.button1.Click += new System.EventHandler(this.button1_Click);
// button2
this.button2.Location = new System.Drawing.Point(96, 80);
this.button2.Name = "button2";
this.button2.TabIndex = 1;
this.button2.Text = "生成 doc";
this.button2.Click += new System.EventHandler(this.button2_Click);
// button3
this.button3.Location = new System.Drawing.Point(8, 32);
this.button3.Name = "button3";
this.button3.TabIndex = 2;
this.button3.Text = "載入 doc";
this.button3.Click += new System.EventHandler(this.button3_Click);
// button4
this.button4.Location = new System.Drawing.Point(8, 80);
this.button4.Name = "button4";
this.button4.TabIndex = 3;
this.button4.Text = "載入 XML";
this.button4.Click += new System.EventHandler(this.button4_Click);
// Form1
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(184, 141);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.Load += new System.EventHandler(this.Form1_Load);
this.Closed += new System.EventHandler(this.Form1_Closed);
}
#endregion
/// <summary>
/// 從這個入口啟動表單
/// </summary>
static void Main()
{
Application.Run(new Form1());
}
/// <summary>
/// 把載入的 Office 文件轉換為 XML 文件
/// </summary>
private void button1_Click(object sender, System.EventArgs e)
{
saveFileDialog1.Filter = "xml 文件|*.xml";
saveFileDialog1.Title = "儲存成 XML 文件";
saveFileDialog1.FileName = "";
saveFileDialog1.ShowDialog();
if( saveFileDialog1.FileName != "" )
{
mXmlDoc.Save(saveFileDialog1.FileName);
MessageBox.Show("儲存成功");
}
}
/// <summary>
/// 把載入的 XML 文件轉換回 Office 文件
/// </summary>
private void button2_Click(object sender, System.EventArgs e)
{
// 從 doc 中取出 me 節點,並讀取其 aa 屬性
XmlNode node = doc.DocumentElement.SelectSingleNode("me");
XmlElement ele = (XmlElement)node;
string pic = ele.GetAttribute("aa");
byte[] bytes = Convert.FromBase64String(pic);
saveFileDialog1.Filter = "Office 文件(*.doc, *.xls, *.ppt)|*.doc;*.xls;*.ppt";
saveFileDialog1.Title = "儲存成 Office 文件";
saveFileDialog1.FileName = "";
saveFileDialog1.ShowDialog();
if( saveFileDialog1.FileName != "" )
{
FileStream outfile = new FileStream(
saveFileDialog1.FileName, System.IO.FileMode.CreateNew );
outfile.Write(bytes, 0, (int)bytes.Length);
outfile.Close();
MessageBox.Show("儲存成功");
}
}
/// <summary>
/// 載入視窗時的初始化行為
/// </summary>
private void Form1_Load(object sender, System.EventArgs e)
{
MessageBox.Show("歡迎使用文件轉換器");
}
/// <summary>
/// 卸載視窗時釋放暫存變數
/// </summary>
private void Form1_Closed(object sender, System.EventArgs e)
{
mXmlDoc = null;
doc = null;
}
/// <summary>
/// 載入 Office 文件並序列化為一個 XmlDocument
/// </summary>
private void button3_Click(object sender, System.EventArgs e)
{
string strFileName;
openFileDialog1.Filter = "Office 文件(*.doc, *.xls, *.ppt)|*.doc;*.xls;*.ppt";
openFileDialog1.FilterIndex = 1;
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
strFileName = openFileDialog1.FileName;
if( strFileName.Length != 0 )
{
FileStream inFile = new FileStream(
strFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read );
byte[] binaryData = new byte[inFile.Length];
inFile.Read(binaryData, 0, (int)inFile.Length);
inFile.Close();
string mStr = Convert.ToBase64String(binaryData);
mXmlDoc = new System.Xml.XmlDocument();
mStr = string.Format("<wawa><me aa=\"{0}\"/></wawa>", mStr);
mXmlDoc.LoadXml(mStr);
MessageBox.Show("載入成功");
}
}
/// <summary>
/// 載入 XML 文件到私有物件 doc
/// </summary>
private void button4_Click(object sender, System.EventArgs e)
{
string strFileName;
openFileDialog1.Filter = "xml 文件|*.xml";
openFileDialog1.FilterIndex = 1;
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
strFileName = openFileDialog1.FileName;
if( strFileName.Length != 0 )
{
doc = new XmlDocument();
doc.Load(strFileName);
MessageBox.Show("載入成功");
}
}
}
}
流程只有兩步:button3 用 FileStream 把二進位檔讀進 byte 陣列,以 Convert.ToBase64String 轉成字串,再塞進 XML 屬性;button2 反向操作,用 FromBase64String 還原位元組並寫回檔案。
有幾處值得調整。第一,把整份檔案塞進單一屬性值,會讓 XML 難以閱讀,實務上建議用元素文字節點承載 Base64,並搭配 xs:base64Binary 型別宣告,讓接收端能直接驗證。第二,範例用字串拼接組出 XML,遇到特殊字元時容易出問題;改用 XmlDocument 的 API 建立節點與屬性,可以省掉所有轉義困擾。第三,FileStream 沒有包在 using 中,例外狀況下檔案控制代碼會洩漏。
最後一點是設計層面的建議:Base64 會讓資料量增加約三分之一,對大型檔案不划算。若環境允許,改用 MTOM 或直接把檔案切塊以訊息佇列傳送,會比整包塞進 XML 更有效率。