File.ReadAllBytes代码重构

Jef*_*ght 3 c# file-io refactoring

我今天遇到了这段代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

我的第一个想法是将其重构为:

public static byte[] ReadContentFromFile(String filePath)
{
    return File.ReadAllBytes(filePath);
}
Run Code Online (Sandbox Code Playgroud)

System.IO.File.ReadAllBytes记录为:

打开二进制文件,将文件内容读入字节数组,然后关闭文件.

...但我错过了一些关键的区别吗?

Jon*_*eet 7

如果文件为空,则原始代码返回空引用,如果无法读取,则不会引发异常.我个人认为最好返回一个空数组,并且不要吞下异常,但这就是重构和重新设计之间的区别.

哦,同样,如果在找出长度和读取长度之间改变文件长度,那么原始代码将读取原始长度.我再次认为这种File.ReadAllBytes行为更好.

如果文件不存在,您希望发生什么?