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?
You can also say:
But some people might find that hard to read. BTW, as an optimization to your problem, why dont you check that the file sizes are the same size first, before going line by line?
When the
IDisposable
s are of the same type, you can do the following:The MSDN page on
using
has documentation on this language feature.You can do the following whether or not the
IDisposable
s are of the same type:If the objects are of the same type you can do the following
There's nothing odd about it.
using
is a shorthand way of ensuring the disposal of the object once the code block is finished. If you have a disposable object in your outer block that the inner block needs to use, this is perfectly acceptable.Edit: Too slow on the typing to show consolidated code example. +1 to everyone else.
You could omit the brackets on all but the inner-most using:
I think this is cleaner than putting several of the same type in the same using, as others have suggested, but I'm sure many people will think this is confusing
if you don't mind declaring the variables for your using block before the using block, you could declare them all in the same using statement.
That way, x and y are just placeholder variables of type IDisposable for the using block to use and you use t and u inside your code. Just thought i'd mention.