From my understanding, ReadAllLines would open a file, and then return all the lines within that file, and then closes that file/stream. Now I have this piece of code:
try
{
string[] lines = File.ReadAllLines(path);
}
catch(IOException)
{
Console.WriteLine("File doesnt exist in : " + path);
}
I did that so that if the file within the path directory doesnt exist, it would throw an error message. My question: is that necessary? Since I dont know how ReadAllLines() was implemented by microsoft, I dont really know if it already had a try catch built-in within the function implementation..
I however, can "guess" that ReadAllLines() would always close the file stream everytime it finishes reading it. that is the reason I did not run the cleanup code that is supposed to be included within the finally{} block.
Can somebody explain/give me confirmation about this? Any help would be appreciated. Let me know if the question is not clear. Thank you.
I looked at the source in ILSpy and it looks like it does the following:
[SecuritySafeCritical]
public static string[] ReadAllLines(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
if (path.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
}
return File.InternalReadAllLines(path, Encoding.UTF8);
}
And the method InternalReadAllLines:
private static string[] InternalReadAllLines(string path, Encoding encoding)
{
List<string> list = new List<string>();
using (StreamReader streamReader = new StreamReader(path, encoding))
{
string item;
while ((item = streamReader.ReadLine()) != null)
{
list.Add(item);
}
}
return list.ToArray();
}
Reading the documentation of the File.ReadAllLines() method helps - all the exceptions that might be thrown are listed there - this includes IOException and FileNotFoundException.
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