Thứ Tư, 28 tháng 8, 2019

Kiểm tra trùng file C# (check duplicate files)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CheckDuplicateFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnFind_Click(object sender, EventArgs e)
    {
        txtResult.Text = CountDuplitcateFiles(txtPath.Text).ToString();
        if (CountDuplitcateFiles(txtPath.Text) > 0)
        {
            //Có file trùng
        }
        else
        {
            //không trùng
        }

        //CheckAndDelete(txtPath.Text);
    }

    static string GetHash(string filePath)
    {
        using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            return Encoding.UTF8.GetString(new SHA1Managed().ComputeHash(fileStream));
        }
    }

    static void CheckAndDelete(string folderPath)
    {
        Directory.GetFiles(folderPath)
            .Select(
            f => new
            {
                FileName = f,
                FileHash = GetHash(f)
            })
            .GroupBy(f => f.FileHash)
            .Select(g => new { FileHash = g.Key, Files = g.Select(z => z.FileName).ToList() })
            .SelectMany(f => f.Files.Skip(1))
            .ToList()
            .ForEach(File.Delete);
    }

    static int CountDuplitcateFiles(string folderPath)
    {
      return Directory.GetFiles(folderPath)
            .Select(
            f => new
            {
                FileName = f,
                FileHash = GetHash(f)
            })
            .GroupBy(f => f.FileHash)
            .Select(g => new { FileHash = g.Key, Files = g.Select(z => z.FileName).ToList() })
            .SelectMany(f => f.Files.Skip(1))
            .ToList().Count();
    }
    protected void btnCompareHash_Click(object sender, EventArgs e)
    {
        string h1 = GetHash(txtPath.Text);
        string h2 = GetHash(txtPath2.Text);
        txtResult.Text = (h1==h2)?"Giong":"Khac";

    }
}

Không có nhận xét nào:

Đăng nhận xét