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;
        }

 

posted @ 2014-07-07 10:58  人生只若初见  阅读(2594)  评论(0编辑  收藏  举报