码迷,mamicode.com
首页 > Windows程序 > 详细

C# 列出并删除一个文件夹下的所有MD5值相同的文件

时间:2015-01-19 20:33:30      阅读:497      评论:0      收藏:0      [点我收藏+]

标签:

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

namespace ConsoleApplication7
{
    class Program
    {
        public static Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();

        static void Main(string[] args)
        {
            string folderPath = @"D:\Temp";
            DirectoryInfo di = new DirectoryInfo(folderPath);
            FileInfo[] fi = di.GetFiles();
            foreach (FileInfo f in fi)
            {
                string md5 = GetMD5HashFromFile(f.FullName);
                if (dic.Keys.Contains(md5))
                {
                    List<string> list = dic[md5];
                    list.Add(f.FullName);
                    dic[md5] = list;
                }
                else
                {
                    List<string> list = new List<string>();
                    list.Add(f.FullName);
                    dic.Add(md5, list);
                }
            }

            foreach (string d in dic.Keys)
            {
                List<string> list = dic[d];
                if (list.Count > 1)
                {
                    Console.WriteLine("----------" + d + "------------");
                    int sign = 1;
                    foreach (string str in list)
                    {
                        Console.WriteLine(str);
                        if (sign != 1)
                        {
                            File.Delete(str);
                        }
                        sign++;
                    }
                    Console.WriteLine("----------------------------------------------------");
                    Console.WriteLine();
                }
            }

        }

        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }
    }
}

 

C# 列出并删除一个文件夹下的所有MD5值相同的文件

标签:

原文地址:http://www.cnblogs.com/mtsl/p/4234507.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!