To create or get a folder from Sharepoint Site the following code snippet can be used:
public static SPFolder CreateORGetFolder( SPWeb web, string listName, string folderUrl)
{
SPList targetList = web.Lists[listName];
if (string.IsNullOrEmpty(folderUrl))
return targetList.RootFolder;
SPFolder folder = targetList.ParentWeb.GetFolder(web.Url + "/" + targetList.RootFolder.Url + "/" + folderUrl);
if (!folder.Exists)
{
if (!targetList.EnableFolderCreation)
{
targetList.EnableFolderCreation = true;
targetList.Update();
} // We couldn't find the folder so create it
string[] folders = folderUrl.Trim('/').Split('/');
string folderPath = string.Empty;
for (int i = 0; i < folders.Length; i++)
{
folderPath += "/" + folders[i];
folder = targetList.ParentWeb.GetFolder(web.Url + "/" + targetList.RootFolder.Url + folderPath);
if (!folder.Exists)
{
SPListItem newFolder = targetList.Items.Add("" , SPFileSystemObjectType.Folder,folderUrl);
newFolder.Update();
folder = newFolder.Folder;
}
}
}
// Still no folder so error out
if (folder == null)
throw new SPException(string.Format("The folder '{0}' could not be found.", folderUrl));
return folder;
}
No comments:
Post a Comment