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.

  • 相关阅读:
    dragloader.js帮助你在页面原生滚动下实现Pull Request操作
    移动Web单页应用开发实践——实现Pull to Request(上/下拉请求操作)
    【转】移动Web单页应用开发实践——页面结构化
    前端网址收集!Amazing! 神奇!
    前端代码书写规范
    扫描工具 分析
    backtrack5渗透 笔记
    Sqlmap注入技巧集锦
    nmap 高级扫描用法
    小温谈数据库优化--数据设计篇(转)
  • 原文地址:https://www.cnblogs.com/wangzhe66369/p/12606065.html
Copyright © 2011-2022 走看看