Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ReadAllLines() function have built in try-catch?

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.

like image 511
Benny Tjia Avatar asked Jul 22 '26 19:07

Benny Tjia


2 Answers

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();
}
like image 136
Daniel Mann Avatar answered Jul 25 '26 07:07

Daniel Mann


Reading the documentation of the File.ReadAllLines() method helps - all the exceptions that might be thrown are listed there - this includes IOException and FileNotFoundException.

like image 41
BrokenGlass Avatar answered Jul 25 '26 08:07

BrokenGlass