Exercise
Mix And Sort Files
Objetive
Create a program that reads the contents of two different files, merges them, and sorts them alphabetically. For example, if the files contain: "Dog Cat and Chair Table", the program should display: "Cat Chair Dog Table".
Example Code
using System;
using System.IO;
using System.Collections;
namespace Text
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter name of file1: ");
string nameFile1 = Console.ReadLine();
Console.Write("Enter name of file2: ");
string nameFile2 = Console.ReadLine();
if ((!File.Exists(nameFile1)) ||
(!File.Exists(nameFile2)))
{
Console.Write("File 1 or File 2 not exists");
return;
}
try
{
StreamReader myfile = File.OpenText(nameFile1);
ArrayList list = new ArrayList();
string line;
do
{
line = myfile.ReadLine();
if (line != null)
list.Add(line);
}
while (line != null);
myfile.Close();
myfile = File.OpenText(nameFile2);
line = "";
do
{
line = myfile.ReadLine();
if (line != null)
list.Add(line);
}
while (line != null);
myfile.Close();
list.Sort();
for (int i = 0; i < list.Count; i++)
Console.WriteLine(list[i]);
}
catch (Exception e)
{
Console.WriteLine("Error al intentar abir el fichero.");
}
}
}
}