Try, catch statement in C# -
i have following c# code calculating each file's hash in certain, user specified directory. point works fine, until encounters file cannot access. when finds this, throws error message , exits program. want instead is, throw error message name of file cannot accessed, write there error in accessing file, , continue executing program other files in directory. if can me edit code , achieve things glad.
private void sha256directory(string directory) { try { sha256 directorysha256 = sha256managed.create(); byte[] hashvalue; directoryinfo dir = new directoryinfo(directory); fileinfo[] files = dir.getfiles(); foreach (fileinfo finfo in files) { filestream fstream = finfo.open(filemode.open); fstream.position = 0; hashvalue = directorysha256.computehash(fstream); console.writeline(finfo.name); miscellaneous.bytearraytohex(hashvalue); miscellaneous.bytearraytobase64(hashvalue); console.writeline(); fstream.close(); } return; } catch(directorynotfoundexception) { console.writeline("error: directory specified not found."); } catch(ioexception) { console.writeline("error: file in directory not accessed."); } catch(argumentnullexception) { console.writeline("error: argument cannot null or empty."); } }
move try/catch inside foreach
. haven't explained in post, i'm guessing that's encounter exception.
in doing so, exception caused code in there caught , allow loop continue.
careful, though -- these 2 lines still not exception-safe:
directoryinfo dir = new directoryinfo(directory); fileinfo[] files = dir.getfiles();
you'll want account well.
if want show file/directory caused issue, tostring
exception, example:
catch(directorynotfoundexception ex) { console.writeline("error: directory specified not found: " + ex.tostring()); }
if tostring
doesn't give desired output, try ex.message
. use tostring
though.
edit credit ken henderson
when using kind of stream
, should put in using
block. garbage collector close
stream eventually, practice this, using
block close stream you're done using it:
using (filestream fstream = finfo.open(filemode.open)) { fstream.position = 0; hashvalue = directorysha256.computehash(fstream); console.writeline(finfo.name); miscellaneous.bytearraytohex(hashvalue); miscellaneous.bytearraytobase64(hashvalue); console.writeline(); } // no need fstream.close() more, using block take care of
Comments
Post a Comment