c# base64及MD5工具类

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace TJCFinanceWriteOff.BizLogic.Common
{
    public class FileUtil
    {

        /// <summary>
        /// 将文件转换为base64String
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static string GetFileBase64(string filePath)
        {
            filePath = filePath  ?? throw new ArgumentException("文件路径错误");

            try
            {
                using(FileStream fs = File.OpenRead(filePath))
                {
                    return GetFileBase64(fs);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 将文件转换为base64String
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static string GetFileBase64(Stream stream)
        {
            stream = stream ?? throw new ArgumentException("参数不能为空");

            try
            {
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                // 设置当前流的位置为流的开始
                stream.Seek(0, SeekOrigin.Begin);
                return Convert.ToBase64String(bytes,0, bytes.Length);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 计算文件的MD5值
        /// 用做于缓存Key
        /// </summary>
        /// <param name="arg">类型只能为string or stream,否则将会抛出错误</param>
        /// <returns>文件的MD5值</returns>
        public static string GetFileMd5(object arg)
        {
            MD5 md5Hash = MD5.Create();
            byte[] data = null;

            switch (arg)
            {
                case string str:
                    data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(str));
                    break;
                case Stream stream:
                    data = md5Hash.ComputeHash(stream);
                    break;
                case null:
                    throw new ArgumentException("参数不能为空");
                default:
                    throw new ArgumentException("参数类型错误");
            }
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            md5Hash.Dispose();
            return sBuilder.ToString();
        }

        /// <summary>
        /// 遍历文件夹获取文件路径
        /// </summary>
        /// <param name="direPath"></param>
        /// <returns></returns>
        public static DataTable GetFilesByDirePath(string direPath)
        {
            DirectoryInfo folder = new DirectoryInfo(direPath);
            if (!folder.Exists)
            {
                throw new DirectoryNotFoundException("文件夹不存在!");
            }

            var datas = (from x in folder.GetFiles()
                         where x.Extension == ".jpg" || x.Extension == ".jpeg"
                         orderby int.Parse(x.Name.Split('.')[0])
                         select x.FullName).ToArray();

            var dt = new DataTable();
            dt.Columns.Add("序号", typeof(int));
            dt.Columns.Add("扫描图片", typeof(string));
            dt.Columns.Add("识别结果", typeof(string));
            DataRow dr = null;
            for (int i = 0; i < datas.Length; i++)
            {
                dr = dt.NewRow();
                dr[0] = i + 1;
                dr[1] = datas[i];
                dr[2] = "未扫描";
                dt.Rows.Add(dr);
            }
            return dt;
        }

        /// <summary>
        /// 将DataTable中的数据转换为base64集合
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string[] GetFilesBase64(DataTable dt)
        {
            List<string> filesBase64Array = new List<string>();
            foreach (DataRow item in dt.Rows)
            {
                filesBase64Array.Add(GetFileBase64(item["扫描图片"].ToString()));
            }
            return filesBase64Array.ToArray();
        }

        /// <summary>
        /// 将图片List以正面 反面 分割
        /// </summary>
        /// <param name="source">源数据List</param>
        /// <param name="obverse">正面图片集合</param>
        /// <param name="reverse">反面图片集合</param>
        public static void SplitList(List<string> source, out List<string> obverse, out List<String> reverse)
        {
            //1.将List一分为二
            obverse = source.Take(source.Count / 2).ToList();
            reverse = source.Skip(source.Count / 2).ToList();
            reverse.Reverse();
        }

        /// <summary>
        /// 将图片List以正面 反面 分割 (备用)
        /// </summary>
        /// <param name="source">源数据List</param>
        /// <param name="obverse">正面图片集合</param>
        /// <param name="reverse">反面图片集合</param>
        public static void SplitListBackup(List<string> source, out List<string> obverse, out List<String> reverse)
        {
            //1.将List一分为二并翻转
            obverse = new Queue<string>(source.Take(source.Count / 2)).ToList();
            reverse = new Stack<string>(source.Skip(source.Count / 2)).ToList();
        }
    }
}

 

posted @ 2019-10-29 09:56  SpringCore  阅读(668)  评论(0编辑  收藏  举报