Hi,
How do I check if the following statement in my C# executed correctly?
StreamReader sr = new StreamReader(Path_To_File);
Hi,
How do I check if the following statement in my C# executed correctly?
StreamReader sr = new StreamReader(Path_To_File);
Because StreamReaders implement IDisposable, you can use a 'using' block.
using(StreamReader sr = new StreamReader(Path_To_File)) {
}
If it didn't, I would expect it to throw an exception. So do nothing; it will tell you if there is a problem. But you should be "using
" it:
using(StreamReader sr = new StreamReader(Path_To_File))
{
// consume sr
}
If it didn't throw an exception, it executed correctly. If it throws an exception, it's reasonable to expect the cosntructor to tidy up after itself. Otherwise, it'll be up to you to call Dispose
on it when you're finished, to release the associated resources. As others answers have said, you almost certainly want to use a using
statement to accomplish this.
You might also want to use File.OpenText
instead:
using (TextReader reader = File.OpenText(fileName))
{
}
I only usually use the StreamReader
constructor when I need to pass in different options (which is pretty rarely).
I may be missing something in the question, because this seems too obvious, but the two things to look for are
If 1 is false and 2 is true, it executed correctly.
You would normally do somthing with the instance sr. Encapsulate your next command which references that object in a try catch block.
The StreamReader constructor (assuming a string path argument) will throw an exception if it fails.
Quoted from the link:
ArgumentException
path is an empty string ("").
ArgumentNullException
path is null.
FileNotFoundException
The file cannot be found.
DirectoryNotFoundException
The specified path is invalid, such as being on an unmapped drive.
IOException path includes an incorrect or invalid syntax for file name, directory name, or volume label.
You'd want to check for exceptions using standard Try / Catch blocks like this:
string pathToFile = @"G:\My Documents\donkeysex.txt";
StreamReader sr = null;
try
{
sr = new StreamReader(pathToFile);
sr.Read();
// etc.
}
catch (System.IO.FileNotFoundException ex)
{
// Handle exception
}
catch (System.IO.DirectoryNotFoundException ex)
{
// Handle exception
}
catch (System.IO.IOException ex)
{
// Handle exception
}
catch (Exception ex)
{
// Handle exception
}
finally
{
if (sr != null)
sr.Dispose();
}
If you just want to ensure the file exists before reading then use:
if (System.IO.File.Exists(pathToFile))
{
// Do your stuff
}