List泛型自定义类型排序和大小比较C#版

想删除一堆大小相同的文件,于是想到用List泛型自定义类型排序和大小比较,准备先大小排序,再比较删除同大小的

1、随便来个自定义类

public class FileSort
    {
        long filesize;

        public long Filesize
        {
            get { return filesize; }
            set { filesize = value; }
        }

        string filepath;

        public string Filepath
        {
            get { return filepath; }
            set { filepath = value; }
        }
    }

2、List list= new List();

    把需要处理的文件信息填进list  //此处代码略

 

3、自定义排序

 private int CompareByFileSize(FileSort x, FileSort y)
        {
            int returnVal = y.Filesize.CompareTo(x.Filesize);
            return returnVal;
        }

        list.Sort(CompareByFileSize);


4、比较大小,删除相同大小的

                int m = 0;
                while (m < list.Count - 1)
                {
                    if (list[m].Filesize == list[m + 1].Filesize)
                    {
                        new FileInfo(list[m + 1].Filepath).Delete();
                        list.RemoveAt(m + 1);
                    }
                    else
                    {
                        m++;
                    }
                }


 5、要是觉得大小相同还不放心的话那就再加个hash吧

我设定一个文件大于16K的话用FileStream读文件开头的16K,小于则全部读进byte[] readBytes

int hash = Encoding.ASCII.GetString(readBytes).GetHashCode(); 比较的话先比大小,大小一样加比hash

                int m = 0;
                while (m < list.Count - 1)
                {
                    if (list[m].Filesize == list[m + 1].Filesize)
                    {
                        if (list[m].Hash == list[m + 1].Hash)
                        {
                             new FileInfo(list[m + 1].Filepath).Delete();
                            list.RemoveAt(m + 1);
                        }
                        else
                        {
                            m++;
                        }
                    }
                    else
                    {
                        m++;
                    }
                }


完整代码

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Text;
using System.ComponentModel;

namespace TEST
{
    public partial class Form1 : Form
    {
        StringBuilder sb = new StringBuilder();

        public Form1()
        {
            InitializeComponent();
            textBox1.Text = "不显示查找速度更快适合大数据量文件操作";
        }

        public void FindFileShow(object o)
        {
            FindParameter fp = (FindParameter)o;
            DirectoryInfo di = new DirectoryInfo(fp.Path);
            FileInfo[] fis = di.GetFiles(fp.Filename);
            DirectoryInfo[] dis = di.GetDirectories();

            foreach (FileInfo i in fis)
            {
                this.Invoke(new MethodInvoker(() => { sb.Append(i.FullName + "\r\n"); textBox1.Text = sb.ToString(); label3.Text = (int.Parse(label3.Text) + 1).ToString(); }));
            }

            foreach (DirectoryInfo i in dis)
            {
                try
                {
                    fp.Path = i.FullName;
                    FindFileShow(fp);
                }
                catch (Exception)
                {
                    //Undo
                }
            }
        }

        public void FindFileHide(object o)
        {
            FindParameter fp = (FindParameter)o;
            DirectoryInfo di = new DirectoryInfo(fp.Path);
            FileInfo[] fis = di.GetFiles(fp.Filename);
            DirectoryInfo[] dis = di.GetDirectories();

            foreach (FileInfo i in fis)
            {
                this.Invoke(new MethodInvoker(() => { sb.Append(i.FullName + "\r\n"); label3.Text = (int.Parse(label3.Text) + 1).ToString(); }));
            }

            foreach (DirectoryInfo i in dis)
            {
                try
                {
                    fp.Path = i.FullName;
                    FindFileHide(fp);
                }
                catch (Exception)
                {
                    //Undo
                }
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            this.Width = 1024;
            this.Height = 768;
        }

        private void textBox2_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("需要手动输入查找路径吗(文件量太大时手动输入可减少不必要的打开时间)?", "手动确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                //Undo
            }
            else
            {
                FolderBrowserDialog fbd = new FolderBrowserDialog();
                if (fbd.ShowDialog() == DialogResult.OK)
                    textBox2.Text = fbd.SelectedPath;
            }
        }

        private int CompareByFileSize(FileSort x, FileSort y)
        {
            int returnVal = y.Filesize.CompareTo(x.Filesize);
            return returnVal;
        }

        private int CompareByHash(FileSort x, FileSort y)
        {
            int returnVal = y.Hash.CompareTo(x.Hash);
            return returnVal;
        }

        private int CompareByFileName(FileSort x, FileSort y)
        {
            int returnVal = y.Filename.CompareTo(x.Filename);
            return returnVal;
        }

        private void 显示目录查找ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            sb = new StringBuilder();
            textBox1.Text = "";
            label3.Text = "0";
            FindParameter fp = new FindParameter();
            fp.Path = textBox2.Text;
            fp.Filename = textBox3.Text;
            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerReportsProgress = false;
            worker.DoWork += (s, o) =>
            {
                FindFileShow(fp);
            };
            worker.RunWorkerCompleted += (s, o) =>
            {
                MessageBox.Show("查找成功!");
            };
            worker.RunWorkerAsync();
        }

        private void 不显示目录查找ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            sb = new StringBuilder();
            textBox1.Text = "不显示查找速度更快适合大数据量文件操作";
            label3.Text = "0";
            FindParameter fp = new FindParameter();
            fp.Path = textBox2.Text;
            fp.Filename = textBox3.Text;
            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerReportsProgress = false;
            worker.DoWork += (s, o) =>
            {
                FindFileHide(fp);
            };
            worker.RunWorkerCompleted += (s, o) =>
            {
                MessageBox.Show("查找成功!");
            };
            worker.RunWorkerAsync();
        }

        private void 删除所有找到ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要删除所有找到文件吗?", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                BackgroundWorker worker = new BackgroundWorker();
                worker.WorkerReportsProgress = true;
                progressBar1.Visible = true;
                progressBar1.Value = 0;
                worker.DoWork += (s, o) =>
                {
                    string[] filepath = sb.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    int k = 1;
                    foreach (string i in filepath)
                    {
                        try
                        {
                            FileInfo fi = new FileInfo(i);
                            fi.Delete();
                        }
                        catch (Exception)
                        {
                            //Undo
                        }
                        worker.ReportProgress((int)((float)k / (float)filepath.Length * 100), null);
                        k++;
                    }
                };
                worker.ProgressChanged += (s, o) =>
                {
                    progressBar1.Style = ProgressBarStyle.Continuous;
                    progressBar1.Value = o.ProgressPercentage;
                };
                worker.RunWorkerCompleted += (s, o) =>
                {
                    progressBar1.Visible = false;
                    MessageBox.Show("删除成功!");
                };
                worker.RunWorkerAsync();
            }
        }

        private void 删除大小重复ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要删除大小重复文件吗?", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                BackgroundWorker worker = new BackgroundWorker();
                worker.WorkerReportsProgress = true;
                progressBar1.Visible = true;
                progressBar1.Value = 0;
                worker.DoWork += (s, o) =>
                {
                    string[] filepath = sb.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    List list = new List();
                    int k = 1;
                    foreach (string i in filepath)
                    {
                        try
                        {
                            FileInfo fi = new FileInfo(i);
                            FileSort fs = new FileSort();
                            fs.Filesize = fi.Length;
                            fs.Filepath = i;
                            list.Add(fs);
                        }
                        catch (Exception)
                        {
                            //Undo
                        }
                        worker.ReportProgress((int)((float)k / (float)filepath.Length * 50), null);
                        k++;
                    }

                    list.Sort(CompareByFileSize);
                    int m = 0;
                    while (m < list.Count - 1)
                    {
                        if (list[m].Filesize == list[m + 1].Filesize)
                        {
                            new FileInfo(list[m + 1].Filepath).Delete();
                            list.RemoveAt(m + 1);
                        }
                        else
                        {
                            m++;
                            worker.ReportProgress((int)((float)m / (float)(list.Count - 1) * 50) + 50, null);
                        }
                    }
                };
                worker.ProgressChanged += (s, o) =>
                {
                    progressBar1.Style = ProgressBarStyle.Continuous;
                    progressBar1.Value = o.ProgressPercentage;
                };
                worker.RunWorkerCompleted += (s, o) =>
                {
                    progressBar1.Visible = false;
                    MessageBox.Show("删除成功!");
                };
                worker.RunWorkerAsync();
            }
        }

        private void 一般精确删除重复ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要一般精确删除重复文件吗?", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                BackgroundWorker worker = new BackgroundWorker();
                worker.WorkerReportsProgress = true;
                progressBar1.Visible = true;
                progressBar1.Value = 0;
                worker.DoWork += (s, o) =>
                {
                    string[] filepath = sb.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    int k = 1;
                    List list = new List();
                    foreach (string i in filepath)
                    {
                        try
                        {
                            FileInfo fi = new FileInfo(i);
                            FileSort fs = new FileSort();
                            fs.Filesize = fi.Length;
                            fs.Filepath = i;
                            FileStream file = fi.OpenRead();
                            byte[] read;
                            if (fi.Length >= 1024 * 16)
                            {
                                read = new byte[1024 * 16];
                                file.Seek(0, SeekOrigin.Begin);
                                file.Read(read, 0, 1024 * 16);
                                file.Close();
                            }
                            else
                            {
                                read = new byte[fi.Length];
                                file.Seek(0, SeekOrigin.Begin);
                                file.Read(read, 0, (int)fi.Length);
                                file.Close();
                            }
                            fs.Hash = Encoding.ASCII.GetString(read).GetHashCode();
                            list.Add(fs);
                        }
                        catch (Exception)
                        {
                            //Undo
                        }
                        worker.ReportProgress((int)((float)k / (float)filepath.Length * 50), null);
                        k++;
                    }
                    list.Sort(CompareByFileSize);
                    int m = 0;
                    while (m < list.Count - 1)
                    {
                        if (list[m].Filesize == list[m + 1].Filesize)
                        {
                            if (list[m].Hash == list[m + 1].Hash)
                            {
                                new FileInfo(list[m + 1].Filepath).Delete();
                                list.RemoveAt(m + 1);
                            }
                            else
                            {
                                m++;
                                worker.ReportProgress((int)((float)m / (float)(list.Count - 1) * 50) + 50, null);
                            }
                        }
                        else
                        {
                            m++;
                            worker.ReportProgress((int)((float)m / (float)(list.Count - 1) * 50) + 50, null);
                        }
                    }
                };
                worker.ProgressChanged += (s, o) =>
                {
                    progressBar1.Style = ProgressBarStyle.Continuous;
                    progressBar1.Value = o.ProgressPercentage;
                };
                worker.RunWorkerCompleted += (s, o) =>
                {
                    progressBar1.Visible = false;
                    MessageBox.Show("删除成功!");
                };
                worker.RunWorkerAsync();
            }
        }

        private void 完全精确删除重复ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要完全精确删除重复文件吗?", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                BackgroundWorker worker = new BackgroundWorker();
                worker.WorkerReportsProgress = true;
                progressBar1.Visible = true;
                progressBar1.Value = 0;
                worker.DoWork += (s, o) =>
                {
                    string[] filepath = sb.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    int k = 1;
                    List list = new List();
                    foreach (string i in filepath)
                    {
                        try
                        {
                            FileInfo fi = new FileInfo(i);
                            FileSort fs = new FileSort();
                            fs.Filesize = fi.Length;
                            fs.Filepath = i;
                            FileStream file = fi.OpenRead();
                            byte[] read = new byte[(int)fi.Length];
                            file.Seek(0, SeekOrigin.Begin);
                            file.Read(read, 0, (int)fi.Length);
                            file.Close();
                            fs.Hash = Encoding.ASCII.GetString(read).GetHashCode();
                            list.Add(fs);
                        }
                        catch (Exception)
                        {
                            //Undo
                        }
                        worker.ReportProgress((int)((float)k / (float)filepath.Length * 50), null);
                        k++;
                    }
                    list.Sort(CompareByFileSize);
                    int m = 0;
                    while (m < list.Count - 1)
                    {
                        if (list[m].Filesize == list[m + 1].Filesize)
                        {
                            if (list[m].Hash == list[m + 1].Hash)
                            {
                                new FileInfo(list[m + 1].Filepath).Delete();
                                list.RemoveAt(m + 1);
                            }
                            else
                            {
                                m++;
                                worker.ReportProgress((int)((float)m / (float)(list.Count - 1) * 50) + 50, null);
                            }
                        }
                        else
                        {
                            m++;
                            worker.ReportProgress((int)((float)m / (float)(list.Count - 1) * 50) + 50, null);
                        }
                    }
                };
                worker.ProgressChanged += (s, o) =>
                {
                    progressBar1.Style = ProgressBarStyle.Continuous;
                    progressBar1.Value = o.ProgressPercentage;
                };
                worker.RunWorkerCompleted += (s, o) =>
                {
                    progressBar1.Visible = false;
                    MessageBox.Show("删除成功!");
                };
                worker.RunWorkerAsync();
            }
        }

        private void 删除旧时间重复文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要删除重复名称旧时间文件吗?", "删除确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                BackgroundWorker worker = new BackgroundWorker();
                worker.WorkerReportsProgress = true;
                progressBar1.Visible = true;
                progressBar1.Value = 0;
                worker.DoWork += (s, o) =>
                {
                    string[] filepath = sb.ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    int k = 1;
                    List list = new List();
                    foreach (string i in filepath)
                    {
                        try
                        {
                            FileInfo fi = new FileInfo(i);
                            FileSort fs = new FileSort();
                            fs.Filename = fi.Name;
                            fs.Filepath = i;
                            fs.Lasttime = fi.LastWriteTimeUtc;
                            list.Add(fs);
                        }
                        catch (Exception)
                        {
                            //Undo
                        }
                        worker.ReportProgress((int)((float)k / (float)filepath.Length * 50), null);
                        k++;
                    }
                    list.Sort(CompareByFileName);
                    int m = 0;
                    while (m < list.Count - 1)
                    {
                        if (list[m].Filename == list[m + 1].Filename)
                        {
                            if (list[m].Lasttime >= list[m + 1].Lasttime)
                            {
                                new FileInfo(list[m + 1].Filepath).Delete();
                                list.RemoveAt(m + 1);
                            }
                            else
                            {
                                new FileInfo(list[m].Filepath).Delete();
                                list.RemoveAt(m);
                            }
                        }
                        else
                        {
                            m++;
                            worker.ReportProgress((int)((float)m / (float)(list.Count - 1) * 50) + 50, null);
                        }
                    }
                };
                worker.ProgressChanged += (s, o) =>
                {
                    progressBar1.Style = ProgressBarStyle.Continuous;
                    progressBar1.Value = o.ProgressPercentage;
                };
                worker.RunWorkerCompleted += (s, o) =>
                {
                    progressBar1.Visible = false;
                    MessageBox.Show("删除成功!");
                };
                worker.RunWorkerAsync();
            }
        }
    }

    public class FindParameter
    {
        string path;

        public string Path
        {
            get { return path; }
            set { path = value; }
        }
        string filename;

        public string Filename
        {
            get { return filename; }
            set { filename = value; }
        }
    }

    public class FileSort
    {
        long filesize;

        public long Filesize
        {
            get { return filesize; }
            set { filesize = value; }
        }

        string filepath;

        public string Filepath
        {
            get { return filepath; }
            set { filepath = value; }
        }

        int hash;

        public int Hash
        {
            get { return hash; }
            set { hash = value; }
        }

        string filename;

        public string Filename
        {
            get { return filename; }
            set { filename = value; }
        }

        DateTime lasttime;

        public DateTime Lasttime
        {
            get { return lasttime; }
            set { lasttime = value; }
        }
    }
}


你可能感兴趣的:(.net)