zoukankan      html  css  js  c++  java
  • C#解码编码大文件

    因为项目中有个需求把文件转成base64,一开始做的思路,是直接把文件读到内存中,然后在内存里转成base64 。 但是因为这个方法是公共方法,考虑到别人也可能用到,如果别人转的是几个G的大文件,那么直接加载到内存中,肯定是不行的,会出现内存溢出。通过网上查找资料,总结整理成下面的方法。
    下面这个方法,我测试的时候,文件大小32G,转成base64,需要20分钟。

    // A code block
    
            /// <summary>
            /// Encode  file content base64
            /// </summary>
            /// <param name="filein">Input file path,The file is unencoded</param>
            /// <param name="fileout">Encoded output file path</param>
            public static void EncodeBase64File(string filein, string fileout)
            {
                try
                {
                    using (FileStream fs = File.Open(fileout, FileMode.Create))
                    using (var cs = new CryptoStream(fs, new ToBase64Transform(), CryptoStreamMode.Write))
                    using (var fi = File.Open(filein, FileMode.Open))
                    {
                        fi.CopyTo(cs);
                    }
                }
                catch (Exception ex)
                {
                    Utils.Log.Warn("EncodeBase64File failed with " + ex.ToString());
                }
            }
    
           /// <summary>
            /// Decode file content base64
            /// </summary>
            /// <param name="filein">Input file path,The file is unencoded</param>
            /// <param name="fileout">Encoded output file path</param>
            public static void DecodeBase64File(string filein, string fileout)
            {
                try
                {
                    using (FileStream fs = File.Open(fileout, FileMode.Create))
                    using (var cs = new CryptoStream(fs, new FromBase64Transform() , CryptoStreamMode.Write))
                    using (var fi = File.Open(filein, FileMode.Open))
                    {
                        fi.CopyTo(cs);
                    }
                }
                catch (Exception ex)
                {
                    Utils.Log.Warn("DecodeBase64File failed with " + ex.ToString());
                }
            }
    

    参考链接1: link.
    参考链接2: link.
    参考链接3: link.

  • 相关阅读:
    重置 Mac 上的 NVRAM 或 PRAM
    为什么我的mac插入耳机耳机没有声音呢?
    Redis 实现安全队列
    设计模式之十三:适配器模式(Adapter)
    关于cocos2dx手游lua文件加密的解决方式
    Django中载入js和css文件
    CCNA 例题精选
    JNI/NDK开发指南(四)——字符串处理
    error when loading the sdk 发现了元素 d:skin 开头无效内容
    Webx学习(一)
  • 原文地址:https://www.cnblogs.com/wangzhe66369/p/12606065.html
Copyright © 2011-2022 走看看