1、需要命名空间
using system.text;
using system.io;
using system.xml;
2、文件夹中存在001.jpg图片
3、生成一个docsave.xml文件
/******************
try
{
xmldocument myxmldoc = new xmldocument();
myxmldoc.loadxml("<picture><name>picture</name></picture>");
xmlelement elem = myxmldoc.createelement("image");
/ 打开图片文件,利用该图片构造一个文件流
filestream fs = new filestream("../../001.jpg",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("../../docsave.xml");
messagebox.show("读写结束!");
catch(exception ex)
{
messagebox.show(ex.tostring());
}
/*************
/生成后的xml文档
/******
<picture>
<name>picture</name>
<image>......</image>
</picture>
/***********
/测试上一程序
/***********
说明:读取docsave.xml中的image节点,将其存为图片格式002.jpg.
try
{
int readbyte = 0;
int bytestoread = 1044;
xmltextreader xmltxtrd = new xmltextreader("../../docsave.xml");
filestream fs = new filestream("../../002.jpg",filemode.create);
binarywriter bw = new binarywriter(fs);
byte[] base64buffer = new byte[bytestoread];
while(xmltxtrd.read())
{
if (xmltxtrd.nodetype == xmlnodetype.element !amp;!amp; 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());
}