将文件用base64编码保存成字符串,并从字符串中还原。

类别:.NET开发 点击:0 评论:0 推荐:

        //

        //  using System;

        //  using System.IO;

        //

 

        /// <summary>

        /// Temporary storage.

        /// </summary>

        private string buffer;

 

 

        /// <summary>

        /// Write base64 string to temp storage.

        /// </summary>

        private void base64Encode( string fromFile )

        {

            FileStream fileStream = File.Open(fromFile , FileMode.Open);

 

            byte[] buffer = new byte[fileStream.Length];

 

            fileStream.Read(buffer, 0, buffer.Length);

 

            fileStream.Close();

 

            this.buffer = Convert.ToBase64String(buffer);

        }

 

        /// <summary>

        /// Read base64 string from temp storage and save to file.

        /// </summary>

        private void base64Decode( string toFile )

        {

            FileStream fileStream = new FileStream(toFile, FileMode.Create);

 

            byte[] buffer = Convert.FromBase64String(this.buffer);

 

            fileStream.Write(buffer, 0, buffer.Length);

 

            fileStream.Close();

        }

 

        /// <summary>

        /// Form event.

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void button1_Click(object sender, EventArgs e)

        {

            this.base64Encode("C:\\plastic.bmp");

        }

 

        /// <summary>

        /// Form event.

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void button2_Click(object sender, EventArgs e)

        {

            this.base64Decode("C:\\tmp.bmp");

        }

本文地址:http://com.8s8s.com/it/it44576.htm