将图⽚保存到XML⽂件的⽅法⼀.保存图⽚到XML⽂件
///<summary>xml文件怎么打开
///保存图⽚到XML⽂件
///</summary>
private void UploadImageToXml()
{
///得到⽤户要上传的⽂件名
string strFilePathName = loFile.PostedFile.FileName;
string strFileName = Path.GetFileName(strFilePathName);
int FileLength = loFile.PostedFile.ContentLength;
if(FileLength<=0)
return;
try
{
///图象⽂件临时储存Byte数组
Byte[] FileByteArray = new Byte[FileLength];
///建⽴数据流对像
Stream StreamObject = loFile.PostedFile.InputStream;
///读取图象⽂件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
StreamObject.Read(FileByteArray,0,FileLength);
///要打开的⽂件
string fileName = Server.MapPath(".\\l");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fileName);
///查<dbGuest>
XmlNode root=xmlDoc.SelectSingleNode("dbImage");
XmlNodeList xnl=xmlDoc.SelectSingleNode("dbImage").ChildNodes;
int nIndex = xnl.Count;
///以下添加新结点
XmlElement xe1=xmlDoc.CreateElement("Image");//创建⼀个<User>节点
XmlElement xesub1=xmlDoc.CreateElement("ImageID");
///设置⽂本节点
xesub1.InnerText=nIndex.ToString();
/
//添加到<User>节点中
xe1.AppendChild(xesub1);
XmlElement xesub2=xmlDoc.CreateElement("ImageContentType");
xesub2.InnerText=loFile.PostedFile.ContentType;
xe1.AppendChild(xesub2);
XmlElement xesub3=xmlDoc.CreateElement("ImageSize");
xesub3.InnerText=FileLength.ToString();
xe1.AppendChild(xesub3);
XmlElement xesub4=xmlDoc.CreateElement("ImageDescription");
xesub4.InnerText=tbDescription.Text;
xe1.AppendChild(xesub4);
XmlElement xesub5=xmlDoc.CreateElement("ImageData");
xesub5.InnerText= Convert.ToBase64String(FileByteArray);
xe1.AppendChild(xesub5);
///添加到<dbGuest>节点中
root.AppendChild(xe1);
xmlDoc.Save(fileName);
Response.Redirect("ShowAllImg.aspx");
}
catch(Exception ex)
{
throw ex;
}
}
⼆.从XML中读取图⽚数据
///<summary>
///从XML中读取图⽚
///</summary>
///<param name="ImageID">图⽚ID</param>
private void ReadImageFromXml(string ImageID)
{
///ID为图⽚ID
int ImgID = Convert.ToInt32(ImageID);
/
//要打开的⽂件
string fileName = Server.MapPath(".\\l");
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(fileName);
XmlNodeList node =  xmlDoc.SelectSingleNode("//Image[ImageID='"+ImgID.ToString()+"']").ChildNodes; if(node!=null)
{
string strType = node.Item(1).InnerText;
string strData =node.Item(4).InnerText;
int nSize = int.Parse(node.Item(2).InnerText);
///设定输出⽂件类型
Response.ContentType = strType;
///输出图象⽂件⼆进制数制
Response.OutputStream.Write(Convert.FromBase64String(strData), 0, nSize);
Response.End();
//也可以保存为图像
//FileStream fs = new FileStream(@"C:\aa.BMP", FileMode.OpenOrCreate, FileAccess.Write);
//fs.Write((Convert.FromBase64String(strData), 0,nSize);
//fs.Close();
}
}