I trying to write a program that navigates the local file system using a config file containing relevant filepaths. My question is this: What are the best practices to use when performing file I/O (this will be from the desktop app to a server and back) and file system navigation in C#?
I know how to google, and I have found several solutions, but I would like to know which of the various functions is most robust and flexible. As well, if anyone has any tips regarding exception handling for C# file I/O that would also be very helpful.
System.IO
is all you need :)As regards exception handling. Unless we are expecting an exception, we should never catch it. Truly unexpected exceptions should go unhandled. [looks guilty] ok, the only exception is at the highest level, and only for reporting purposes, such as
If you are expecting an exception then one of the following is acceptable
or
There are various classes you can use in the
System.IO
namespace, includingFile
,FileInfo
,Directory
, andDirectoryInfo
.As for practices... as with any IO, make sure you close any streams you open. You also may need to utilize a
Disposable
object, so look into theusing
keyword.You don't need a separate library, use the classes in the
System.IO
namespace likeFile
,FileInfo
,Directory
,DirectoryInfo
. A simple example:What various libraries are you talking about?
I would pretty much stick to
System.IO.Directory
and such. It has everything you need.Something like: