C# 获取txt文件邮箱号码并去重复

2020-08-19 14:35:00 浏览数 (1)

这是咱们C# 开发交流群里好友昨天提的问题:

主要是从txt文件中删除重复的邮箱号

以下是实现的代码:

代码语言:javascript复制
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        string dataPath = @"C:UsersadminDesktop111";
        public void FileReadWriter(string filePath)
        {
            if (Directory.Exists(filePath))

            {

                string[] filenames = Directory.GetFiles(filePath);

                foreach (string fname in filenames)
                {

                    FileInfo finfo = new FileInfo(fname);
                    List<string> posts = new List<string>();
                    if (finfo.Name.Substring(finfo.Name.Length - 4, 4) == ".txt")
                    {
                        foreach (string str in File.ReadAllLines(finfo.FullName, Encoding.Default))
                        {
                            posts.Add(str);
                        }
                        HashSet<string> hs = new HashSet<string>(posts);//此时已经去掉重复的数据保存在hashset中 方法1
                        posts = posts.Distinct().ToList();// 方法2
                        StreamWriter sw = new StreamWriter(finfo.FullName, false);
                        foreach (var post in posts) //方法1
                        {
                            sw.WriteLine(post);
                        }
                        //foreach (var post in hs)//方法2
                        //{
                        //    sw.WriteLine(post);
                        //}

                        sw.Close();
                    }


                }
            }

        }
        public void FileWriter(string filePath)
        {


        }

            private void button1_Click(object sender, EventArgs e)
        {
            FileReadWriter(dataPath);

            MessageBox.Show("文件去重完成");

        }
    }
}

运行效果:

0 人点赞