Existence of Folder and Files in SharePoint

From time to time in your SharePoint code, you are required to determine the existence of files and folders. This becomes important when developing WebParts / integrated SharePoint applications that will work with storage mediums in SharePoint such as SharePoint Document Libraries. Developing these types of conditional tests just means creating a Boolean test that will pass in a file name or a folder name that is a string which is used as a comparison operator. It is not real fancy, but can enhance your code in order to eliminate un-necessary loops and possibly reduce existence test execution bloat.

Firstly, you have to declare the Boolean file test, which is going to be static, taking in the folder and the filename as the parameters.

When declaring the Boolean folder test, you can do something similar in order to determine whether a folder contains a certain subfolder, however you are going to be passing the folder name in as a string as opposed to the filename.

Once the test has been declared, the loop has to be declared in order to iterate through the relevant objects. The first loop is going to use a foreach declaration using the SPFile class. The SPFile class can be used in order to represent a file that exists within a document library, which is based against a certain SharePoint folder, SPFolder, which was passed as a parameter.

Similarly, you can determine the existence of a folder within a set of subfolders with a similar approach. The only difference between the two loops are that you are using SPFolder to instantiate the loop in the folder iteration, and SPFile to instantiate the loop in the previous sample.

Lastly, you must declare the comparison operator in order to determine whether the file name exists or not. Otherwise, you will just be looping and not doing any type of operation to test for the certain set.

Small, and somewhat simplistic, piece of code, but very useful at times, I keep it in a shared library, as I recommend you should do to utilize throughout modules when you find it necessary. Once you have the loops done, you just have to set the code to return true; or return false; based on the conditions that you setup previously.