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.

  • 相关阅读:
    一些网站后台模板源码分析 Particleground.js 验证码
    C# 接口的作用浅谈举例(转)
    C# 批量修改文件名
    12306抢票软件相关接口以及数据格式
    StackExChange.Redis for C# 中文文档
    asp.net core 3+ 修改view后自动重新编译运行
    ASP.NET MVC https全局配置
    c#DateTime与unix时间戳互相转换
    mongodb创建管理员用户
    Office365激活方法(无需密钥)
  • 原文地址:https://www.cnblogs.com/wangzhe66369/p/12606065.html
Copyright © 2011-2022 走看看