代码改变世界

将图片的二进制文件存入xml文件。

2009-08-03 18:12  lome  阅读(509)  评论(0编辑  收藏  举报

string imageFileName = @"C:\pic\lilies.jpg";

   try
   {
    XmlTextWriter writer;
    string strFilename = Server.MapPath("data1.xml") ;
    writer = new XmlTextWriter(strFilename,Encoding.Default);

    //Start writing the XML document
    writer.Formatting = Formatting.Indented;
    writer.WriteStartDocument();
    writer.WriteStartElement("employee");                   
    writer.WriteStartElement("image");
    
    //Get the size of the file  
    FileInfo fi = new FileInfo(imageFileName);
    int size = (int)fi.Length;                          
    
    //Read the JPEG file    
    byte[] imgs = new byte[size];
    FileStream fs = new FileStream(imageFileName,FileMode.Open);
    BinaryReader reader = new BinaryReader(fs);
    imgs = reader.ReadBytes(size);
    reader.Close();
 
    writer.WriteBase64(imgs, 0, size);                      
    
    writer.WriteEndElement();
    writer.WriteEndElement();                  
    writer.WriteEndDocument();

    writer.Flush();
   }     
   catch (Exception ex)
   {
    throw ex;
   }

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

读取二进制文件从xml文件。

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 string file = @"D:\UploadImage\abc.gif";

    XmlDocument doc = new XmlDocument();
   doc.Load(Server.MapPath("data1.xml"));
   byte[] Img = Convert.FromBase64String(doc.SelectSingleNode("/employee/image").InnerText);

   MemoryStream ms = new MemoryStream(Img);
   Bitmap b = (Bitmap)System.Drawing.Image.FromStream(ms);
   b.Save(file,System.Drawing.Imaging.ImageFormat.Gif);

   #region 另一种方法创建文件
   int length = Img.Length;
   FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write);
   fs.Write(Img, 0, length);
   fs.Flush();
   fs.Close();
   #endregion