Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.ReadAllBytes Code Refactoring

I came across this piece of code today:

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 refactor it down to this:

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 am I missing some key difference?

like image 578
Jeffrey Knight Avatar asked Dec 16 '25 15:12

Jeffrey Knight


1 Answers

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

Oh, also, if the file length is changed between finding out the length and reading it, then the original code will read the original length. Again, I think the File.ReadAllBytes behaviour is better.

What do you want to happen if the file doesn't exist?

like image 92
Jon Skeet Avatar answered Dec 19 '25 04:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!