using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 选择一个图片文件,然后写进XML中(提前准备好一个空的XML文件pic.xml放在应用程序目录中)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
DialogResult oK = openFileDialog1.ShowDialog() ;
if (oK == DialogResult.OK)
{
try
{
XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.Load( Application.StartupPath + "\\pic.xml");
XmlElement elem = myXmlDoc.CreateElement("image");
// 打开图片文件,利用该图片构造一个文件流
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open);
// 使用文件流构造一个二进制读取器将基元数据读作二进制值
BinaryReader br = new BinaryReader(fs);
byte[] imageBuffer = new byte[br.BaseStream.Length];
br.Read(imageBuffer, 0, Convert.ToInt32(br.BaseStream.Length));
string textString = System.Convert.ToBase64String(imageBuffer);
fs.Close();
br.Close();
XmlText text = myXmlDoc.CreateTextNode(textString);
myXmlDoc.DocumentElement.AppendChild(elem);
myXmlDoc.DocumentElement.LastChild.AppendChild(text);
myXmlDoc.Save(Application.StartupPath + "\\docSave.xml");
MessageBox.Show("读写结束!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
/// <summary>
/// 选择一个XML文件,读取后保存成文件。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
DialogResult oK = saveFileDialog1.ShowDialog();
if (oK == DialogResult.OK)
{
try
{
int readByte = 0;
int bytesToRead = 1044;
XmlTextReader xmlTxtRd = new XmlTextReader(Application.StartupPath + "\\docSave.xml");
FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
byte[] base64buffer = new byte[bytesToRead];
while (xmlTxtRd.Read())
{
if (xmlTxtRd.NodeType == XmlNodeType.Element && xmlTxtRd.Name == "image")
{
do
{
readByte = xmlTxtRd.ReadBase64(base64buffer, 0, bytesToRead);
bw.Write(base64buffer, 0, readByte);
}
while (bytesToRead <= readByte);
}
}
bw.Flush();
bw.Close();
fs.Close();
xmlTxtRd.Close();
MessageBox.Show("读写结束!");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
}