c# - Why does Code Analysis tell me, "Do not dispose objects multiple times" here: -
on code:
public static string base64fromfilename(string filename) { seek { 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(); homecoming convert.tobase64string(bdata); } catch(exception e) { throw e; } }
...i get, courtesy of visual studio's code analysis tool, warning, "do not dispose objects multiple times...to avoid generating system.objectdisposedexception should not phone call dispose more 1 time on object" on "fstream.close();" line.
why? fstream disposed in line above, binaryreader closed?
wouldn't improve off refactoring anyway:
. . . 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(); . . .
?
binaryreader.close
closes underlying stream, indeed cause stream disposed of twice. that's not real problem, disposing twice doesn't hurt.
you write much improve as
using (var fs = new filestream(filename, filemode.open, fileaccess.read)) using (var br = new binaryreader(fs, new utf8encoding(), true)) { homecoming convert.tobase64string(br.readbytes((int)numbytes)); }
this bomb-proof version:
anything constructed guaranteed disposed you won't dispose of stream twice because booleanleaveopen
argument on binaryreader
constructor ensures disposing (closing) won't close stream c# visual-studio-2013 filestream dispose binaryreader
No comments:
Post a Comment