System.IO is all you need :)
Regarding exception handling. If we do not expect an exception, we will never catch it. Truly unexpected exceptions should be unhandled. [looks guilty] normal, the only exception is at the highest level and only for reporting purposes, for example
If you expect an exception, then one of the following is valid:
// example of first option. this applies ONLY when there is a // well-defined negative path or recovery scenario public void SomeFunction () { try { string allText = System.IO.File.ReadAllText (); } // catch ONLY those exceptions you expect catch (System.ArgumentException e) { // ALWAYS log an error, expected or otherwise. _log.Warn ("Argument exception in SomeFunction", e); // if the use-case\control flow is recoverable, invoke // recovery logic, preferably out of try-catch scope } }
or
// example of second option. this applies ONLY when there is no // well defined negative path and we require additional information // on failure public void SomeFunction () { try { string allText = System.IO.File.ReadAllText (); } // catch ONLY those exceptions you expect catch (System.ArgumentException innerException) { // do whatever you need to do to identify this // problem area and provide additional context // like parameters or what have you. ALWAYS // provide inner exception throw new SomeCustomException ( "some new message with extra info.", maybeSomeAdditionalContext, innerException); // no requirement to log, assume caller will // handle appropriately } }
source share