我有一个事件接收器,当用户创建文件夹时,它会自动创建 13 个子文件夹。下面的代码可以做到这一点,当管理员帐户创建文件夹时一切正常。但是当涉及到其他用户时,不会在没有任何错误的情况下创建子文件夹。
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
SPWeb web = properties.OpenWeb();
web.AllowUnsafeUpdates = true;
SPDocumentLibrary docLib = (SPDocumentLibrary)web.List[properties.ListId];
if (properties.ListItem.ContentType.Name == "Folder"
&& properties.ListItem.Folder.ParentFolder.ToString().ToLower().EndsWith("opportunity"))
{
String url = properties.ListItem.ParentList.RootFolder.ServerRelativeUrl.ToString();
SPFolder libFolder = properties.ListItem.Folder;
string newFolderUrl = (web.Url + "/" + libFolder.ToString());
foreach (string subfolder in folders)
{
SPListItem newFolder = docLib.Items.Add(newFolderUrl, SPFileSystemObjectType.Folder, subfolder);
newFolder.Update();
}
}
}
我阅读了许多关于提升 SPSite 和 SPWeb 的帖子,并在创建子文件夹之前编写了一个代码来提升对象。但是下面的代码不起作用:
public override void ItemAdded(SPItemEventProperties properties)
{
Guid siteId = properties.SiteId;
Guid webId = properties.OpenWeb().ID;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite elevatedSite = new SPSite(siteId))
{
using (SPWeb web = elevatedSite.OpenWeb(webId))
{
base.ItemAdded(properties);
web.AllowUnsafeUpdates = true;
SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists[properties.ListId];
if (properties.ListItem.ContentType.Name == "Folder"
&& properties.ListItem.Folder.ParentFolder.ToString().ToLower().EndsWith("opportunity"))
{
String url = properties.ListItem.ParentList.RootFolder.ServerRelativeUrl.ToString();
SPFolder libFolder = docLib.RootFolder.SubFolders[properties.ListItem.Name];
SPFolder libFolder = properties.ListItem.Folder;
string newFolderUrl = (web.Url + "/" + libFolder.ToString());
foreach (string subfolder in folders)
{
SPListItem newFolder = docLib.Items.Add(newFolderUrl, SPFileSystemObjectType.Folder, subfolder);
newFolder.Update();
}
}
web.AllowUnsafeUpdates = false;
}
}
});
}
任何人都可以帮助解决问题吗?请注意,所有用户都是家庭成员,可以手动创建文件夹。