Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Text.RegularExpressions;
- using System.Security;
- //Write a program that removes from a text file all words listed in given another text file. Handle all possible exceptions in your methods.
- class RemoveWords
- {
- static void Main()
- {
- try
- {
- List<string> words = new List<string>();
- using (StreamReader reader = new StreamReader("words.txt"))
- {
- ReadWords(reader, words);
- }
- using (StreamReader reader = new StreamReader("file.txt"))
- using (StreamWriter writer = new StreamWriter("result.txt"))
- {
- DeleteMatches(reader, writer, words);
- }
- }
- catch (FileNotFoundException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (DirectoryNotFoundException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (IOException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (UnauthorizedAccessException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (ArgumentNullException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (ArgumentException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (OutOfMemoryException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (NotSupportedException err)
- {
- Console.WriteLine(err.Message);
- }
- catch (SecurityException err)
- {
- Console.WriteLine(err.Message);
- }
- }
- private static void DeleteMatches(StreamReader reader, StreamWriter writer, List<string> words)
- {
- string line;
- while ((line = reader.ReadLine()) != null)
- {
- foreach (string item in words)
- {
- line = Regex.Replace(line, "\\b" + item + "\\b", string.Empty);
- }
- writer.WriteLine(line);
- }
- }
- private static void ReadWords(StreamReader reader, List<string> words)
- {
- string line;
- while ((line = reader.ReadLine()) != null)
- {
- string[] word = line.Split();
- foreach (string item in word)
- {
- words.Add(item);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement