当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > .Net中将图片数据保存到XML文档

ASP.NET
为T-SQL添加intellisense功能
SQL Server 2005安装过程中出现错误的解决办法
SQL Server 2005 RTM 安装错误 :The SQL Server System Configuration Checker cannot be executed due to
有关于JSON的一些资料
不能忽略c#中的using和as操作符的用处
JavaScript系列之―同步还是异步?
获取远程网页的内容之一(downmoon原创)
获取远程网页的内容之二(downmoon原创)
ASP.Net中防止刷新自动触发事件的解决方案
asp.net下用js实现鼠标移至小图,自动显示相应大图
Asp.Net 和 AJAX.Net 的区别
提交页面的定位--scrollIntoView的用法
利用AJAX与数据岛实现无刷新绑定
asp.net下判断用户什么时候离开,以什么方式离开
DataSet 添加数据集、行、列、主键和外键等操作示例
读写xml所有节点个人小结 和 读取xml节点的数据总结
收藏的asp.net文件上传类源码
asp.net下GDI+的一些常用应用(水印,文字,圆角处理)技巧
一个可以让.net程序在非WIN平台上运行的软件Mono
使用ASP.NET 2.0 CSS 控件适配器生成CSS友好的HTML输出

ASP.NET 中的 .Net中将图片数据保存到XML文档


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 100 ::
收藏到网摘: n/a

  因为最近要做的项目中,我要通过XML动态生成窗体,看了UI图样,我有些叫苦:我通过XML动态生成窗体,可是主窗体中UI要用图标来确定要使用的窗体,怎么才能使主窗体的图标也是动态加载而且图标和要生成的窗体还有关联呢?我又想到用XML,查MSDN,看到只有XmlTextWriter和XmlTextReader里分别有XmlTextWriter.WriteBase64和XmlTextReader.ReadBase64可以操作图片这种二进制字节的数据。但是XmlTextWriter和XmlTextReader远不如XmlDocument操作方便,如果用这两者我就得写太多的代码。
困扰了我一天,记得以前看到过一篇文章介绍怎样将图片数据存储到Xml文件,可是怎么也找不到,后来终于在一个英文网站上找到了相关内容,而且还是2003年贴出来的,汗。
好了,不废话了,我把我的实现代码贴给大家吧。
private XmlDocument document;
private string FilePath = Application.StartupPath + "\\..\\..\\FormStyle.xml";   // FormStyle.xml 文件地址
 
private void frmMain_Load(object sender, System.EventArgs e)
{
       if(document == null)
       {
              document = new XmlDocument();
              document.Load(FilePath);
       }
 
       // 只挑选含有Form的节点
       XmlNodeList FormNodes = document.GetElementsByTagName("Form");
       lbIcons.BeginUpdate();
       lbIcons.Items.Clear();
       foreach(XmlNode node in FormNodes)
       {
              // 把节点的名称放到下拉列表里
              lbIcons.Items.Add(node.Attributes["Name"].Value);
       }
       lbIcons.EndUpdate();
}
 
private void lbIcons_SelectedValueChanged(object sender, System.EventArgs e)
{
       // 查找下拉框所选的窗体下是否有Image元素,若无则退出
       XmlNode node = document.DocumentElement.SelectSingleNode(string.Format("descendant::Form[@Name='{0}']/Image", lbIcons.SelectedItem.ToString()));
       if(node == null)
              return;
 
       // 如果含有Image元素,就将元素值转换为Base64String,然后放到内存流
       using (MemoryStream mem = new MemoryStream(Convert.FromBase64String(node.InnerText)))
       {
              // 加载内存流数据为位图
              Bitmap bmp = Bitmap.FromStream(mem) as Bitmap;
              pictureBox1.Image = bmp;
       }
}
 
private void btnAdd_Click(object sender, System.EventArgs e)
{
       // 如果不存在txtFilePath.Text所指文件,就退出
       if(!File.Exists(txtFilePath.Text) || lbIcons.Items.Count == 0)
              return;
 
       if(lbIcons.SelectedIndex == -1)
              lbIcons.SelectedIndex = 0;
 
       if(document == null)
       {
              document = new XmlDocument();