利用Base64编码,可把任意类型文件转为类型数据流进行传输 利用Base64编码,可把任意类型文件转为类型数据流进行传输

2016-06-11

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Drawing;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;

public partial class FileStreamxx : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {


        this.Label1.Text = ToBase64FileStream("05.zip");

        this.FileStreamToFile(this.Label1.Text, "aa.zip");
    }

    /// <summary>
    /// 把文件转为数据流 字符串
    /// </summary>
    /// <param name="filename"></param>
    /// <returns></returns>
    protected string ToBase64FileStream(string filename)
    {
        //读取一个文件
        FileStream fs = new FileStream(Server.MapPath(filename), System.IO.FileMode.Open, System.IO.FileAccess.Read);
        byte[] filecontent = new byte[fs.Length];
        fs.Read(filecontent, 0, filecontent.Length);
        fs.Close();
        fs.Dispose();
        string backstr = Convert.ToBase64String(filecontent);
        return backstr;
    }
    /// <summary>
    /// 将数据流(字符串)还原为原文件
    /// </summary>
    /// <param name="Base64FileStreamstr"></param>
    /// <param name="FileName"></param>
    /// <returns></returns>
    protected bool FileStreamToFile(string Base64FileStreamstr, string FileName)
    {
        try
        {
            byte[] filecontent2 = Convert.FromBase64String(Base64FileStreamstr);
            //写入目录
            File.WriteAllBytes(Server.MapPath(FileName), filecontent2);
            return true;
        }
        catch
        {
            return false;
        }
    }
}