How do I add a folder to current document library (well if the folder does not exists in the current document library)?
(Current being where ever the end user is) (I am going to add this code to itemAdded event handler)
How do I add a folder to current document library (well if the folder does not exists in the current document library)?
(Current being where ever the end user is) (I am going to add this code to itemAdded event handler)
curSPList.Items.Add("My Folder Name", SPFileSystemObjectType.Folder);
will create a new folder in any SharePoint list, including a document library. If you plan on implementing this in an event handler you can get the reference to the SPList from the "List" property of the SPItemEventProperties parameter.
I tried this per your suggestion but nothing happens when I upload an item to a document library. I tried all of this combination and nothing seems to be working....
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
using (SPSite currentSite = new SPSite(SPContext.Current.Site.Url))
using (SPWeb currentWeb = currentSite.OpenWeb(SPContext.Current.Web.Url))
{
try
{
//SPListTemplateCollection coll = currentWeb.ListTemplates;
//this should get the current document library
SPList newList = currentWeb.GetList(SPContext.Current.Web.Url);
//.Site.Url);
//newList = currentWeb.Lists.Add("My TEST Folder",SPFileSystemObjectType.Folder);
newList.Lists.Items.Add("My TEST Folder", SPFileSystemObjectType.Folder);
newList.Update();
//SPListItem newListItem;
//newListItem = newList.Folders.Add("", SPFileSystemObjectType.Folder, "My Test Folder");
// newListItem = newList.Folders.Add(newList.ToString(), SPFileSystemObjectType.Folder, "My Test Folder");
//newListItem.Update();
}
catch (SPException spEx)
{
throw spEx;
}
}
}
That answer does not work. Please provide full details when answering. I spent too much time investigating thinking this will work. Frustrated...
Here is the final code that works. Creates a Folder "uHippo" in the current document library if "uHippo" does not exists.
public override void ItemAdded(SPItemEventProperties properties) { base.ItemAdded(properties);
using (SPSite currentSite = new SPSite(properties.WebUrl))
using (SPWeb currentWeb = currentSite.OpenWeb())
{ SPListItem oItem = properties.ListItem;
string doclibname = "Not a doclib";
//Gets the name of the document library
SPList doclibList = oItem.ParentList;
if (null != doclibList)
{
doclibname = doclibList.Title;
}
bool foundFolder = false; //Assume it isn't there by default
if (doclibList.Folders.Count > 0) //If the folder list is empty, then the folder definitely doesn't exist.
{
foreach (SPListItem fItem in doclibList.Folders)
{
if (fItem.Title.Equals("uHippo"))
{
foundFolder = true; //Folder does exist, break loop.
break;
}
}
}
if (foundFolder == false)
{
SPListItem folder = doclibList.Folders.Add(doclibList.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, "uHippo");
folder.Update();
}
}
}