Tuesday, July 28, 2009

Reading a text file in C#?

hi ,





How do i read two different text input files using C# console application , also i want to compare both the files line by line for equality and print any lines that are not equal in the output.





please help ....





thank you

Reading a text file in C#?
Hello,





To read a file in C# you could use the built in .NET methods for the Static class called File. It would help you compare both files line by line easier. It is strictly made for Reading files the efficient way. To do that, you simply do:





string[] linesFirstFile = File.ReadAllLines("myFirstFile.txt");





To compare files, you need to be aware if one file has more lines than the other, if they do you need to check that so you wont get out of bounds exception. I will show you the proper way to achieve this.





You can add more filtering such as Trim the line for extra spaces (remove spaces from beginning and ending) remove line breaks etc.





But the following example will show you how to read two different files and find the difference between them and print them.








The formatted code is available here: http://mohamed.mansour.pastebin.com/f1fc...


============


// Store contents of the first file to an array


string[] linesFirstFile = File.ReadAllLines("myFirstFile.txt");


// Store contents of the second file to an array


string[] linesSecondFile = File.ReadAllLines("mySecondFile.txt");





// Find out which file has most lines and save that number for iteration


int maxNumberOfLines = linesFirstFile.Length %26gt; linesSecondFile.Length ? linesFirstFile.Length : linesSecondFile.Length;





// Loop through those lines


for (int i = 0; i %26lt; maxNumberOfLines; i++)


{


// Check boundaries in case one file has more or less lines than the other


// Print out EOF (end of file) if it is


string firstLine = linesFirstFile.Length %26gt; i ? linesFirstFile[i] : "{EOF}";


string secondLine = linesSecondFile.Length %26gt; i ? linesSecondFile[i] : "{EOF}";





// Check if both lines are not equal so we print them


if (!firstLine.Equals(secondLine))


{


Console.WriteLine("File 1 (line={0}): {1}", i + 1,firstLine);


Console.WriteLine("File 2 (line={0}): {1}", i + 1, secondLine);


}


}


====================





Good luck, hope this helped
Reply:use streamreader object (system.io.streamreader)


No comments:

Post a Comment