doc文档的Base64 编码及解码

1   string filepath = String.Format("{0}\\{1}\\"+docTitle, mapPath, fileName);//获取要编码的文档的物理路径
2   string newFilePath = String.Format("{0}\\{1}\\NewFile.doc", mapPath, fileName);//解码的文档存放的物理路径
3   if (File.Exists(filepath))
4    {
5         String srcBt = EncodeFileToString(filepath);//调用编码方法
6         DecodeBaseCodeToFile(srcBt, newFilePath);//调用解码方法
    } 
        /// <summary>
        /// 将文件进行 Base64 编码并返回
        /// </summary>
        /// <param name="srcFile">源文件,即要编码的文件的位置</param>
        /// <remarks></remarks>
        public String EncodeFileToString(String srcFile)
        {
            Byte[] srcBt;
            FileStream srcFS = new FileStream(srcFile, FileMode.Open);
            srcBt = new byte[srcFS.Length];
            srcFS.Read(srcBt, 0, srcBt.Length);
            srcFS.Close();
            String destStr = EncodeToByte(srcBt);
            return destStr;
        }
        public String EncodeToByte(Byte[] bt)
        {
            return System.Convert.ToBase64String(bt);
        }
        /// <summary>
        /// 将Base64 解码进行转文件
        /// </summary>
        /// <param name="srcFile">源文件,即要编码的文件的位置</param>
        /// <param name="desFile">目标文件, 编码后的文件要保存的位置, 如果目标文件已经存在, 将会被覆盖</param>
        /// <remarks></remarks>
        public void DecodeBaseCodeToFile(String srcBase64Code, String desFile)
        {
            //读取源内容
            Byte[] myBt = DecodeToByte(srcBase64Code);

            if (File.Exists(desFile))
            {
                File.Delete(desFile);
            }
            //将源内容写入文件
            using (FileStream fs = new FileStream(desFile, FileMode.CreateNew))
            {
                fs.Write(myBt, 0, myBt.Length);
            }
        }
        public Byte[] DecodeToByte(String content)
        {
            Byte[] bt = System.Convert.FromBase64String(content);
            return bt;
        }
        /// <summary>
        /// 将文件进行二进制编码并返回
        /// </summary>
        /// <param name="srcFile">源文件,即要编码的文件的位置</param>
        /// <remarks></remarks>
        public Byte[] EncodeFileToString1(String srcFile)
        {
            FileStream srcFS = new FileStream(srcFile, FileMode.Open, FileAccess.Read);
            Stream sm = srcFS;
            byte[] bytes = new byte[sm.Length];
            sm.Read(bytes, 0, Convert.ToInt32(sm.Length));
            sm.Flush();
            sm.Close();
            return bytes;
        }

 

转载于:https://www.cnblogs.com/jinaczg/p/3829254.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值