为什么Code Analysis告诉我,"不要多次丢弃对象":

B. *_*non 2 c# dispose filestream binaryreader visual-studio-2013

在这段代码上:

public static string Base64FromFileName(string fileName)
{
    try
    {
        FileInfo fInfo = new FileInfo(fileName);
        long numBytes = fInfo.Length;
        FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fStream);
        byte[] bdata = br.ReadBytes((int)numBytes);
        br.Close();
        fStream.Close();
        return Convert.ToBase64String(bdata);
    }
    catch(Exception e)
    {
        throw e;
    }
}
Run Code Online (Sandbox Code Playgroud)

...我得到了Visual Studio的代码分析工具,警告," 不要多次丢弃对象......为了避免生成System.ObjectDisposedException,你不应该在对象上多次调用Dispose " fStream.Close();" 线.

为什么?fStream是否在上面的行中,BinaryReader关闭了?

无论如何,我不会更好地重构它:

. . .
using (FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))   
{
    using (BinaryReader br = new BinaryReader(fStream)) 
    {
        byte[] bdata = br.ReadBytes((int)numBytes);
    } //br.Close();
} //fStream.Close();
. . .
Run Code Online (Sandbox Code Playgroud)

Jon*_*Jon 5

BinaryReader.Close也会关闭底层流,所以这确实会导致流被处理两次.但这不是一个真正的问题,两次处理不会造成伤害.

你可以写得更好

using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
using (var br = new BinaryReader(fs, new UTF8Encoding(), true))
{
    return Convert.ToBase64String(br.ReadBytes((int)numBytes));
}
Run Code Online (Sandbox Code Playgroud)

这是防弹版:

  • 保证成功建造任何东西
  • 您不会将流处理两次,因为构造leaveOpen函数上的布尔参数BinaryReader确保处理(关闭)它也不会关闭流