Code refactoring File.ReadAllBytes

Today I came across this piece of code:

public static byte[] ReadContentFromFile(String filePath)
{
    FileInfo fi = new FileInfo(filePath);
    long numBytes = fi.Length;
    byte[] buffer = null;
    if (numBytes > 0)
    {
        try
        {
            FileStream fs = new FileStream(filePath, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            buffer = br.ReadBytes((int)numBytes);
            br.Close();
            fs.Close();
        }
        catch (Exception e)
        {
            System.Console.WriteLine(e.StackTrace);
        }
    }
    return buffer;
}

My first thought is to reorganize this into the following:

public static byte[] ReadContentFromFile(String filePath)
{
    return File.ReadAllBytes(filePath);
}

System.IO.File.ReadAllBytes is documented as:

Opens a binary file, reads the contents of the file into a byte array, and then closes the file.

... but will I miss some key difference?

+3
source share
3 answers

The source code returns a null reference if the file is empty, and will not throw an exception if it cannot be read. Personally, I think it's better to return an empty array and not swallow exceptions, but I think the difference is between refactoring and redesigning.

, , , . , , File.ReadAllBytes .

, ?

+7

, try {...} catch{...}. , ReadContentFromFile, .

... , unit test?

+2

. . , .

.

. - , .

+1

Source: https://habr.com/ru/post/1719741/


All Articles