SharePoint 2010: Accessing a Creating\Accessing a specific folder in Document Library
Here is the piece of code that I wrote to access a folder inside another folder. Although it could be generalized to n folder by making it recursively call itself but for this specific project it was required to have only 2 folder i.e. we have only two levels of hierarchy. So I wrote a very simple code.
Anyways the description can be found in the comments of the code.
If somebody needs to reach to a multiple hierarchies, then this can code can be modified to a recursive functions.
Hope this helps
Suggestions/Comments are appreciated.
Cheers
Anyways the description can be found in the comments of the code.
protected void Page_Load(object sender, EventArgs e)
public static SPFolder CreateFolder(SPWeb web, string listName, string folderName)
web.AllowUnsafeUpdates = true;
SPList targetList = web.Lists[listName];
if (string.IsNullOrEmpty(folderName))
return targetList.RootFolder;
SPFolder folder = targetList.ParentWeb.GetFolder(web.Url + "/" + targetList.RootFolder.Url + "/" + folderName);
/Checking whether the first level folder exist.
if (!folder.Exists)
{
if (!targetList.EnableFolderCreation)
{
targetList.EnableFolderCreation = true;
targetList.Update();
// Since we could not find the folder so create it
SPListItem userFolder = null;
userFolder = targetList.Items.Add(targetList.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, folderName);
userFolder["Title"] = folderName;
userFolder.Update();
SPListItem hoursFolder = targetList.Items.Add(web.Url + "/" + targetList.RootFolder.Url + "/" + folderName, SPFileSystemObjectType.Folder, DateTime.Now.Year.ToString());
hoursFolder["Title"] = DateTime.Now.Year.ToString();
hoursFolder.Update();
folder = hoursFolder.Folder;
return folder;
}
else{
//In case the first level folder exists then check for the folder inside it
folder = targetList.ParentWeb.GetFolder(web.Url + "/" + targetList.RootFolder.Url + "/" + folderName + "/" + DateTime.Now.Year.ToString());
if (!folder.Exists)
{
SPListItem hoursFolder = targetList.Items.Add(web.Url + "/" + targetList.RootFolder.Url + "/" + folderName, SPFileSystemObjectType.Folder, DateTime.Now.Year.ToString());
hoursFolder["Title"] = DateTime.Now.Year.ToString();
hoursFolder.Update();
folder = hoursFolder.Folder;
return folder;
}
if (folder == null)
throw new SPException(string.Format("The folder '{0}' could not be found.", folderName));
return folder;
}
If somebody needs to reach to a multiple hierarchies, then this can code can be modified to a recursive functions.
Hope this helps
Suggestions/Comments are appreciated.
Cheers
Comments
Post a Comment