C# 计算MD5值

原创
2016/12/11 21:52
阅读数 2.4K

这里输入代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CSharp1
{
    class MD5
    {

        /// <summary>
        /// 计算文件的 MD5 值
        /// </summary>
        /// <param name="fileName">要计算 MD5 值的文件名和路径</param>
        /// <returns>MD5 值16进制字符串</returns>
        public static string SHA256File(string fileName)
        {
            System.Security.Cryptography.MD5.Create();
            return HashFile(fileName, "sha256");
        }
        
        /// <summary>
        /// 计算文件的哈希值
        /// </summary>
        /// <param name="fileName">要计算哈希值的文件名和路径</param>
        /// <param name="algName">算法:sha1,md5</param>
        /// <returns>哈希值16进制字符串</returns>
        public static string HashFile(string fileName, string algName)
        {
            if (!System.IO.File.Exists(fileName))
                return string.Empty;

            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            byte[] hashBytes = HashData(fs, algName);
            fs.Close();
            return ByteArrayToHexString(hashBytes);
        }

        /// <summary>
        /// 计算哈希值
        /// </summary>
        /// <param name="stream">要计算哈希值的 Stream</param>
        /// <param name="algName">算法:sha1,md5</param>
        /// <returns>哈希值字节数组</returns>
        public static byte[] HashData(Stream stream, string algName)
        {
            HashAlgorithm algorithm;
            if (algName == null)
            {
                throw new ArgumentNullException("algName 不能为 null");
            }
            if (string.Compare(algName, "sha1", true) == 0)
            {
                algorithm = SHA1.Create();
            }
            else if (string.Compare(algName, "sha256", true) == 0)
            {
                algorithm = SHA256.Create();
            }
            else if (string.Compare(algName, "md5", true) == 0)
            {
                algorithm = System.Security.Cryptography.MD5.Create();
            }
            else
            {
                throw new Exception("algName 只能使用 sha1 , sha256 或 md5");
            }
            return algorithm.ComputeHash(stream);
        }

        /// <summary>
        /// 字节数组转换为16进制表示的字符串
        /// </summary>
        public static string ByteArrayToHexString(byte[] buf)
        {
            string returnStr = "";
            if (buf != null)
            {
                for (int i = 0; i < buf.Length; i++)
                {
                    returnStr += buf[i].ToString("X2");
                }
            }
            return returnStr;
        }
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace CSharp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string currentDir = Directory.GetCurrentDirectory();
            Console.WriteLine("create dir:"+currentDir);
            string startPath = @"d:\tmp\abc";

            string md5Path = @"d:\tmp\1.md5";
            string extractPath = @"c:\example\extract";

            //DirectoryInfo dir = new DirectoryInfo(startPath);
            //createHideDir(startPath);
            List<string> f_list = getAllScriptFiles();
            foreach (var f in f_list)
            {
                string a = MD5.HashFile(f, "md5");
                Console.WriteLine($"File:{f}, md5:{a}" );
                Write(md5Path, a);
            }
            string fileContent = File.ReadAllText(md5Path);
            Console.WriteLine("fileContent:" + fileContent+ "Length:"+fileContent.Length);
            Console.ReadKey();
        }

        public static  List<string> getAllScriptFiles()
        {
            List<string> file_list = new List<string>();
           //遍历指定目录下的所有文件
           DirectoryInfo dir = new DirectoryInfo(@"d:\tmp\SSH.NET");
            foreach (var each in dir.GetFiles())
            {
                Console.WriteLine("File:" + each.FullName);
                file_list.Add(each.FullName);
            }
            return file_list;
        }

        public static void Write(string path, string content)
        {
            FileStream fs = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            sw.Write(content+"\n");
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }

        public static void createHideDir(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
                Console.WriteLine("create dir success.");
            }
            DirectoryInfo dir = new DirectoryInfo(path);
            dir.Attributes = dir.Attributes | FileAttributes.Hidden;
        }
      

        /// <summary>
        /// 压缩目录
        /// </summary>
        /// <param name="dir"></param>
        public static void Compress(DirectoryInfo dir)
        {
            foreach (FileInfo fileToCompress in dir.GetFiles())
            {
                Compress(fileToCompress);
            }
        }
        /// <summary>
        /// 解压缩目录
        /// </summary>
        /// <param name="dir"></param>
        public static void Decompress(DirectoryInfo dir)
        {
            foreach (FileInfo fileToCompress in dir.GetFiles())
            {
                Decompress(fileToCompress);
            }
        }
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="fileToCompress"></param>
        public static void Compress(FileInfo fileToCompress)
        {
            using (FileStream originalFileStream = fileToCompress.OpenRead())
            {
                if ((File.GetAttributes(fileToCompress.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
                {
                    using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
                    {
                        using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
                        {
                            originalFileStream.CopyTo(compressionStream);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 解压缩文件
        /// </summary>
        /// <param name="fileToDecompress"></param>
        public static void Decompress(FileInfo fileToDecompress)
        {
            using (FileStream originalFileStream = fileToDecompress.OpenRead())
            {
                string currentFileName = fileToDecompress.FullName;
                string newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length);

                using (FileStream decompressedFileStream = File.Create(newFileName))
                {
                    using (GZipStream decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress))
                    {
                        decompressionStream.CopyTo(decompressedFileStream);
                    }
                }
            }
        }
    }




}

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading;

namespace CSharp1 { class CheckHost {

    Dictionary<string, bool> ssh_info = new Dictionary<string, bool>();
    List<Thread> pool = new List<Thread>();
    System.Timers.Timer aTimer = new System.Timers.Timer();


    public CheckHost()
    {
        this.initParams();
        this.initPool();
        
        
    }



    public void showResult()
    {
        int success = 0;
        int fail = 0;
        foreach (bool each in ssh_info.Values)
        {
            if (each)
                success++;
            else
                fail++;
        }

        Console.WriteLine($"SUCCESS: {success}, FAIL:{fail}");
    }








    private void initParams()
    {
        this.ssh_info.Add("172.28.0.2", false);
        this.ssh_info.Add("172.28.0.3", false);
        this.ssh_info.Add("172.28.0.4", false);

        aTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimeEvent);
        aTimer.Interval = 10000;
        aTimer.Enabled = true;
        aTimer.Start(); //开始计时
    }

    private void initPool()
    {
        Thread t;
        foreach (var each in ssh_info.Keys)
        {
            t = new Thread((new ParameterizedThreadStart(CheckHostFunc)));
            pool.Add(t);
            Console.WriteLine("try to start:" + each);
            t.Start(each);
        }
    }

    //该函数用于监控host的连接性
    private void CheckHostFunc(object info)
    {
        //检查host是否可用
        string key = (string)info;
        Console.WriteLine(DateTime.Now + "-start to run host: " + key);
        //设置为可以连接
        Thread.Sleep(2000);
        ssh_info[key] = true;
        Thread.Sleep(30000);
        Console.WriteLine(DateTime.Now + "-END to run host: " + key);
    }

    private void OnTimeEvent(object sender, EventArgs e)
    {
        Console.WriteLine("enter time action: " + DateTime.Now);
        foreach (Thread t in this.pool)
        {
            if (t != null && t.IsAlive)
            {
                Console.WriteLine(t.ToString() + " aborted!");
                t.Abort();
            }
        }
        //释放计时器
        aTimer.Dispose();
        Console.WriteLine("leave time action:" + DateTime.Now);
    }

}

}

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部