复制代码 代码如下:
try
{
int readByte = 0; //
int bytesToRead = 100; //数据缓冲区大小
string fileName = "../../WriteXml.xml"; //要打开的文件
// this.textBox1.Text = string.Empty;
// 打开图片文件,利用该图片构造一个文件流
FileStream fs = new FileStream("../../001.jpg",FileMode.Open);
// 使用文件流构造一个二进制读取器将基元数据读作二进制值
BinaryReader br = new BinaryReader(fs);
XmlTextWriter xmlTxtWt = new XmlTextWriter(fileName,Encoding.UTF8);
//输出设置 代码缩进
xmlTxtWt.Formatting = Formatting.Indented;
// xmlTxtWt.Indentation = 4;
//书写声明
xmlTxtWt.WriteStartDocument();
xmlTxtWt.WriteStartElement("picture","ContactDetails","//www.zyiz.net");//定义命名空间
xmlTxtWt.WriteStartElement("image"); //定义节点
xmlTxtWt.WriteAttributeString("imageName","002.jpg"); //添加图片属性
byte[] base64buffer = new byte[bytesToRead]; //开辟缓冲区
do
{
readByte = br.Read(base64buffer,0,bytesToRead); //将数据读入字节数组
xmlTxtWt.WriteBase64(base64buffer,0,readByte); //将数组中二进制值编码为Base64并写出到XML文件
}while(bytesToRead <= readByte);
xmlTxtWt.WriteEndElement();
xmlTxtWt.WriteEndElement();
xmlTxtWt.WriteEndDocument();
// xmlTxtWt.Flush();
xmlTxtWt.Close();
MessageBox.Show("读写结束!");
// this.textBox1.Text = ReadXml(fileName);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}