Every once in a while you have to work with files. This article will teach you how to check wheter or not file is readable or writeable. You’re also going to learn how to check if given file or directory exists.
Quick intro to C#
All four classes reside inside
System.IO namespace. It’s important to notice the differences between those clasesses, especially in terms of
File class is used to manipulate files. You can use it to create, write to and delete a file. You can also get file attributes. It’s a static class without constructor, so you have to pass a path to a file in each method call.
FileInfo is used to manipulate files, so you can create, write to and delete a file. This class however is not static, you have to create instance of it and you pass a path to file in constructor.
The difference between
DirectoryInfo is basically the same as the difference between
FileInfo. Former is a static class used to operate on directories and latter requires you to create instance for each path.
Check if file exists
Check if directory exists
Test if path is a file or directory
One way to do it is to check wheter or not file/directory exists. It comes with a drawback however, because it won’t tell you explicitly if the path is a file/directory or if it simply doesn’t exist. In order to make sure that the tested path is directory (or file) and it exists we need to test it both ways. I have wrapped it all together into single method:
The second method which we can use is to get path file/directory attributes. Note that when file or directory does not exists it will throw
It’s also worth noting that file attributes are also exposed via
Verify if file is read-only
It’s pretty easy to check read-only file flag using attributes:
Check if file is readable or writeable
Wheter a file can be read or not depends on multiple factors. The following example is simplified, but you should take into account that:
- file may not exists
- file could be locked by some other process
- someone/something can change access to a file during execution of your applications
- you may not have proper permissions (file may belong to other user)
- in case of errors it will throw exceptions
FileStream is disposeable so remember to disposed it afterwards, in this case we’re using the using statement.