Create a folder in document library using Sharepoint event receiver

谁说胖子不能爱 提交于 2019-12-06 07:03:23

问题


I am using the following code to create a folder inside my document library. The event get triggered and executed till the last line of my code without any issues. However the folder is not getting created or listed in my document library.

public override void ItemAdded(SPItemEventProperties properties)
{
    base.ItemAdded(properties);        

    string strDashListRoot = "http://win-hmpjltdbh5q:37642";
    using (SPSite site = new SPSite(strDashListRoot))
    {
        using (SPWeb web = site.OpenWeb())
        {
            web.AllowUnsafeUpdates = true;                    

            SPList spl = web.Lists["client_documents"];
            spl.Items.Add("", SPFileSystemObjectType.Folder, "Helllworld");
            spl.Update();
            web.AllowUnsafeUpdates = false;
        }
    }           
}

回答1:


You need

var i = spl.Items.Add("", SPFileSystemObjectType.Folder, "Helllworld");
i.Update(); 

instead of

spl.Items.Add("", SPFileSystemObjectType.Folder, "Helllworld");
spl.Update();

(assuming your Add call is fine - it looks OK to me)

(Also, are you sure you need the AllowUnsafeUpdates handling? I wouldn't have expected it to be necessary when you're in an ItemAdded handler.)




回答2:


I developed the following code based on Rawling's answer:

private static void CreateFolder(SPWeb web, SPList spList, SPListItem currentItem, string folderName)
{
    if (currentItem.FileSystemObjectType != SPFileSystemObjectType.Folder)
    {
        string itemUrl = web.Url + "/" + currentItem.Url.Substring(0, currentItem.Url.LastIndexOf('/'));

        var folder = spList.Items.Add(itemUrl, SPFileSystemObjectType.Folder, folderName);
        string folderUrl = itemUrl + "/" + folder.Name;

        if (!FolderExists(folderUrl, web))
        {
            try
            {
                folder.Update();
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}


public static bool FolderExists(string url, SPWeb web)
{
    if (url.Equals(string.Empty))
    {
        return false;
    }

    try
    {
        return web.GetFolder(url).Exists;
    }
    catch (ArgumentException)
    {
        throw;
    }
    catch (Exception)
    {
        throw;
    }
}


来源:https://stackoverflow.com/questions/12676531/create-a-folder-in-document-library-using-sharepoint-event-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!