Wednesday, April 8, 2015

Filtering and copying emails to a .txt file from all the .txt files in a Directory

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

namespace FilesExamples
{
    class EmailFilter
    {
        public static void emas()
        {

            try
            {
                string FolderPath = @"D:\Practice Applications\Supported Files\randomemailtext\filtered\Input path";
                string line;
                var Outputdirectory = new DirectoryInfo(@"D:\Practice Applications\Supported Files\randomemailtext\filtered");
                // Loop to search all the .txt files in the directory path
                foreach (string file in Directory.EnumerateFiles(FolderPath, "*.txt"SearchOption.AllDirectories))
                {
                    StringReader srr = new StringReader(File.ReadAllText(file));
                    string dynamicFile = "OutputSample" + ".txt";

                    var Ofile = new FileInfo(Path.Combine(Outputdirectory.FullName, dynamicFile));
                    using (Stream stream = Ofile.OpenWrite())
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        Console.WriteLine("Copying, Please Wait...");
                        while ((line = srr.ReadLine()) != null)
                        {
                            const string MatchEmailPattern =
                            @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
                            + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";
                            Regex rx = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                            // Find matches.
                            MatchCollection matches = rx.Matches(line);
                            // Report the number of matches found.
                            int noOfMatches = matches.Count;
                            // Report on each match.

                            foreach (Match match in matches)
                            {
                                writer.Write(match.Value + "\r\n");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

No comments:

Post a Comment