I am working on a project. I have to compare the contents of two files and see if they match each other precisely.
Before a lot of error-checking and validation, my first draft is:
DirectoryInfo di = new DirectoryInfo(Environment.CurrentDirectory + "\\TestArea\\"); FileInfo[] files = di.GetFiles(filename + ".*"); FileInfo outputFile = files.Where(f => f.Extension == ".out").Single<FileInfo>(); FileInfo expectedFile = files.Where(f => f.Extension == ".exp").Single <FileInfo>(); using (StreamReader outFile = new StreamReader(outputFile.OpenRead())) { using (StreamReader expFile = new StreamReader(expectedFile.OpenRead())) { while (!(outFile.EndOfStream || expFile.EndOfStream)) { if (outFile.ReadLine() != expFile.ReadLine()) { return false; } } return (outFile.EndOfStream && expFile.EndOfStream); } }
It seems a little odd to have nested using
statements.
Is there a better way to do this?
Nesting of a while loop is allowed, which means you can use while loop inside another while loop. However, it is not recommended to use nested while loop because it is difficult to maintain and debug. Example: C#
The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.
The using statement guarantees that the object is disposed in the event an exception is thrown. It's the equivalent of calling dispose in a finally block.
The preferred way to do this is to only put an opening brace {
after the last using
statement, like this:
using (StreamReader outFile = new StreamReader(outputFile.OpenRead())) using (StreamReader expFile = new StreamReader(expectedFile.OpenRead())) { ///... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With