Deleting all inherit sub-folders permission and reassigning to specific group

Hi,
i am trying to assign sub-folders level permission in sharepoint document library. Want to delete all previous inherit permission first and then assign  sub-folders permission to specific group. i am having problem with following code, cannot make a
call to the function. Could you tell me what should i modify the code to work properly.
Thanks in advanced
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace ManageFolderLevelPermission
    class FolderLeverPermission
        static void Main(string[] args)
            //Connect to Sharepoint Site
            SPSite oSPSite = new SPSite("http://nyc01d1sp:8080/");
            //Open Sharepoint Site
            SPWeb web = oSPSite.OpenWeb("/hr/DI/");
            //Get the Sharepoint list item for giving permission
            foreach(SPFolder folder in web.GetFolder("http://nyc01d1sp:8080/hr/DI/docs/").SubFolders);
            setPermissions();
        private static void setPermissions(SPFolder folder,SPSite oSPSite, SPWeb web)
            SPGroupCollection spc = web.SiteGroups;
            //Break the role inheritance in order to assign individual rights on folders
            if (!folder.Item.HasUniqueRoleAssignments)
                folder.Item.BreakRoleInheritance(true);
            while (folder.Item.RoleAssignments.Count > 0)
                try
                    folder.Item.RoleAssignments.Remove(0);
                catch (Exception)
                    break;
            //Role Assignment For the Current User
            SPUser CurrentUser = SPContext.Current.Web.CurrentUser;
            SPGroup group = spc["GroupName"];
            SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)CurrentUser);
            roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions.GetByType(SPRoleType.Administrator));
            folder.Item.RoleAssignments.Add(roleAssignment);
            //Role Assignment for the Group "Contentteam - Management"
            roleAssignment = new SPRoleAssignment((SPPrincipal)group);
            roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions.GetByType(SPRoleType.Administrator));
            folder.Item.RoleAssignments.Add(roleAssignment);            
            oSPSite.AllowUnsafeUpdates = true;
            folder.Item.Update();

Hi Hemendra,
Thanks for your reply. Actually i am trying to do two things here. First i am creating sub-folders using following code. And then trying to assign individual group permission on these sub-folders using following Powershell script. Now problem is when i am
creating sub-folders, its also inheriting all the parent permission. Lets say i have customer folder name "Pepsi" and it has 4 sub-folders (like Account Management, Legal Drafts, Executed.. etc) . Now i want to assign individual group permission to each Sub-folder
but root folder (Pepsi) should remain all the parent permissions. i did try to remove the permission first and then assigned permission to sub-folders. i was able to assign individual group permission to sub-folders but problem is, its also assigning Limited
Access to the root folder. so basically i cannot see the folder as the root folder has limited access. Please let me know how can achieve that.
using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
namespace Add_SubFolders
    class CreateFolders
        static void Main(string[] args)
            var foldersList=new List<string>();
            SPSecurity.RunWithElevatedPrivileges(delegate()
                try
                    using (SPSite site = new SPSite("http://nyc01d1sp:8080/"))
                        using (SPWeb web = site.OpenWeb("/lel/DB/"))
                            web.AllowUnsafeUpdates = true;
                                foreach (SPFolder folder in web.GetFolder("http://nyc01d1sp:8080/lel/DB/docs").SubFolders)
                                    if (folder.Url.ToString() != "/docs/Forms" && folder.Url.ToString() != "/docs/")
                                        foldersList.Add(folder.Url);
                                        SPFolder subFolder = web.GetFolder(folder.Url);
                                        Console.WriteLine("SubFolder is creating.....");
                                        subFolder.SubFolders.Add("Account Management");
                                        subFolder.SubFolders.Add("Legal Drafts");
                                        subFolder.SubFolders.Add("Executed");
                                        subFolder.SubFolders.Add("Sales");
                                    folder.Update();
                                    Console.WriteLine("SubFolder has been created");
                                web.AllowUnsafeUpdates = false;
                catch (Exception ex)
                    ex.Message.ToString();
  Power Shell Script to assign individual group to specific folders:
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
  #$site = new-object Microsoft.SharePoint.SPSite("http://nyc01d1sp:8080/lel/DB/")
  #$site = Get-SPSite ("http://nyc01d1sp:8080/")
  $web= Get-SPWeb("http://nyc01d1sp:8080/")
  #$web = $site.OpenWeb()
  function GrantGroupPermission($groupName)
   [Microsoft.SharePoint.SPGroupCollection]$spgroups = $web.SiteGroups
   [Microsoft.SharePoint.SPGroup]$spgroup = $spgroups[$groupName]
   Write-Host $spgroup.Name -ForegroundColor Red
   $sproleass=new-object Microsoft.SharePoint.SPRoleAssignment([Microsoft.SharePoint.SPPrincipal]$spgroup)
   $folder.BreakRoleInheritance("true")
   $sproleass.RoleDefinitionBindings.Add($web.RoleDefinitions["Contribute"])
   $folder.RoleAssignments.Add($sproleass);
   Write-Host "Permission provided for group ", $groupName
  $doclib=[Microsoft.SharePoint.SPDocumentLibrary]$web.Lists["Shared Documents"]
  $foldercoll=$doclib.Folders;
  foreach($folder in $foldercoll)
   Write-Host $folder.Name
   if($folder.Name.Equals("Account Management"))
    GrantGroupPermission("Test Group")
   if($folder.Name.Equals("Executed"))
    GrantGroupPermission("Legal Group")
   if($folder.Name.Equals("Legal Drafts"))
    GrantGroupPermission("Legal Group")
   if($folder.Name.Equals("Sales"))
    GrantGroupPermission("Sales Group")
  Write-Host "Completed...."
  $web.Close()
  $web.Dispose()
  #$site.Dispose()

Similar Messages

  • Switch to BT Mail has deleted all my sub-folders

    I have just moved from BT Yahoo to BT Mail, following the instructions BT provided. On my PC I use Windows Live Mail. Previously, all my (thousands of) emails were organised into numerous sub-folders dropping down from the Inbox tab, so I knew where everything was. These have all been deleted so all my emails are now in one big mass in the Inbox. Also, I don't have any emails received prior to 2010, and I'm sure there were some there before. Can anyone help?

    If it was a POP3 account, which I suspect it was because most folk set up Windows Live Mail as a POP3 account, you will have lost all your sub folders when you deleted it.  Luckily you still had the emails on the server which enabled them to be downloaded when you re-made the account. It would however not remake the folder structure as this was on your PC within the email account that you deleted.
    You could try searching for the emails by going to Start > Search > type .eml into the search box. This should find all the Windows Live Mail emails on your computer.
    If it was an IMAP account, this would have replicated the folder structure that was set up on the email sever unlike a POP account folders which are on your PC. When you deleted and re-made the account this would have set up the folder structure as it was previously because it replicates the folders on the email server. Because it has not done this is another reason why I suspect your deleted account was a POP3 account. If it was IMAP you would have the folders that you had previously.
    It may be that if it was an IMAP account that you had, the folders could still set up although I have my doubts. You could try a computer restart to see if it sets them up.
    As regards the pre 2010 emails, they may have been deleted from the server by you at some point so they would not now be there to be downloaded.

  • I've deleted all of mail, including trash and sent folders, but my mail usage stays high at around 1.4 gb. What am I missing?

    I've deleted all of mail, including trash and sent folders, but my mail usage stays high at around 1.4 gb. What am I missing?

    It is possible it just hasn' updated yet.
    Try resetting:
    Hold the Sleep/Wake and Home buttons and don’t let go until the screen goes dark and the Apple logo appears (no data will be lost)

  • How can I collapse all my sub-folders when bookmarking a page?

    In Safari when I go to bookmark a page all my sub-folders and their own sub-folders are shown,
    Is there a way to collapse them all into just the main folders and then being able to choose the correct sub-folder from them to bookmark the page.
    I have about 50 main folders but a few hundred sub-folders so when I go to bookmark a page it's very time consuming and annoying.
    In Firefox just the main folders are shown, so I just choose the main folder and expand that and choose the appropriate sub-folder, Job done in seconds!
    Many thanks in advance [ I hope! :-) ]

    Mackem55 wrote:
    Is there a way to collapse them all into just the main folders and then being able to choose the correct sub-folder from them to bookmark the page.
    None that I know about.

  • How do I get all my sub-folders from Yahoo to show up in Mozilla

    I installed Mozilla Thunderbird on my Home PC and Office Laptop. On my PC all my sub-folders were imported automatically. On my Laptop Thunderbird is not showing all the sub-folders I use in Yahoo to keep my emails organized. This is not the local folders that I can set up in Thunderbird. It's the folders I have created in Yahoo for years.

    Pop mail accounts can only connect to server, check Inbox for new messages and download from the server Inbox to the mail account Inbox in Thunderbird. This is how all pop mail accounts work.
    You can get other emails in other folders downloaded by logging on to webmail and moving the emails back into the Inbox and then click GetMail.
    Suggest you do this one folder at a time.
    Imap mail accounts see a remote view of the server folders. You subscribe to see folders. You can also choose to synchronize folders.
    If you want to see various server folders then you have to use IMAP.
    You cannot change a pop into an imap, there are many differences.
    Create a new exisiting mail account and make sure it is an IMAP setting before you click on 'Done'. Use 'Manual config' button if necessary to change settings.

  • How do i delete all my music folders?

    I have just got a new laptop and the people in store moved my music from my old laptop to my new one. They managed to create 2 of everything and now I can't sort it out. I have tried uninstalling apple to reinstall it but it just saved all my previous libraries so I have the same problem! Can i delete all my music folders and start again from scratch? Please help? I am not very IT literate so need all the help I can get?

    These are two possible approaches that will normally work to move an existing library to a new computer.
    Method 1
    Backup the library with this User Tip.
    Deauthorize the old computer if you no longer want to access protected content on it.
    Restore the backup to your new computer using the same tool used to back it up.
    Keep your backup up-to-date in future.
    Method 2
    Connect the two computers to the same network. Share your <User's Music> folder from the old computer and copy the entire iTunes library folder into the <User's Music> folder on the new one. Again, deauthorize the old computer if no longer required.
    Both methods should give the new computer a working clone of the library that was on the old one. As far as iTunes is concerned this is still the "home" library for your devices so you shouldn't have any issues with iTunes wanting to erase and reload.
    I'd recommend method 1 since it establishes an ongoing backup for your library.
    If you have an iOS device that syncs with contact & calendar data on your computer you should migrate this information too. If that isn't possible create a dummy entry of each type in your new profile and iTunes should offer to merge the existing data from the device into the computer, otherwise the danger is that it will wipe the information from the device.
    If your media folder has been split out from the main iTunes folder you may need to do some preparatory work to make it easier to move. See make a split library portable.
    Should you be in the unfortunate position where you are no longer able to access your original library, or a backup of it, then see Recover your iTunes library from your iPod or iOS device for advice on how to set up your devices with a new library with the maximum preservation of data. If you don't have any Apple devices then see HT2519 - Downloading past purchases from the App Store, iBookstore, and iTunes Store.
    tt2

  • I have a iPhone 5.  In usage, it says i have 2.1 gigs used because of photos and camera.  I have deleted all my photos via iPhoto and now reset the phone back to factory settings in order to try to solve this problem, to no avail. Help!

    I have a iPhone 5.  In usage, it says i have 2.1 gigs used because of photos and camera.  I have deleted all my photos via iPhoto and now reset the phone back to factory settings in order to try to solve this problem, to no avail.   Both iTunes  and the phone say that 2.1 gigs are being used, even though the phone now has nothing on it.  What is going on?

    Yeah it works fine over wifi the problem is when I try to use it over my 3G. It's really stressing me out now.

  • My 16gb iPhone 4S keep tell me that my storage is almost full and I don't have enough space for any upgrades. I don't have any music or videos on my phone. I deleted all old emails, texts, contacts and apps but still nothing. When I check my settings, I n

    My 16gb iPhone 4S keep tell me that my storage is almost full and I don't have enough space for any upgrades. I don't have any music or videos on my phone. I deleted all old emails, texts, contacts and apps but still nothing. When I check my settings, I noticed that my Instagram is at 732mb and it keeps rising. Now it's at 814mb. Please help!!!!!

    What is the precise wording of the message that is occurring?
    Are  you attempting to update via iTunes on a computer or over the air on the device?
    How much free space is actually on the device?
    If updating via iTunes on the computer, how much free space on the computer?

  • How can i Delete all foto from my iphone and after some time get them one more time on it but not as a new album :)?

    How can i Delete all foto from my iphone and after some time get them one more time on it but not as a new album, i want them in the camera roll ?

    How can I delete EVERY THING off my Mac and have it like new?
    Boot from the software install DVD and do an "erase and install" when prompted.

  • I've deleted all my mail in iCloud and also empty trash, but iCloud mail still occupied my iCloud storage for 1.9GB. What do I do?

    Dear All,
    I've deleted all my mail in iCloud and also empty trash, but iCloud mail still occupied my iCloud storage for 1.9GB. What do I do?
    BR.

    Hi OaksterMe,
    In order to completely delete emails from your devices and free up space in iCloud, you should follow the steps in this article -
    iCloud: Reduce email storage space
    Thanks for using Apple Support Communities.
    Best,
    Brett L 

  • I just synced my iPhone on iCloud and it deleted all of my calendar events and isn't even showing up on the iCloud website. Is there a way to get all of those events back?

    I just synced my iPhone on iCloud and it deleted all of my calendar events and isn't even showing up on the iCloud website. Is there a way to get all of those events back?

    I've had the same problem, synced yesterday and I've lost all my events in my calendar. Restored my phone,not worked, deleted icloud that hasnot worked,nothing is coming up at all on icloud calendar, and my mac was backed up when I plugged in today so not backed up on that. Someone please help, can I get them back? my life was on that calendar.

  • How do i put tv programmes and videos from itunes to another iphone, without having to delete all data on the phone and replacing it with my library? i switched the 'sync only ticked songs and videos box' yet it still wont let me transfer videos from my i

    How do i put tv programmes and videos from itunes to another iphone, without having to delete all data on the phone and replacing it with my library? i switched the 'sync only ticked songs and videos' yet it still wont let me transfer videos from my itunes onto my new phone, any ideas??

    Copy the entire itunes folder from the old computer to the new computer.

  • BPM question - Delete all entries in a table and Insert data

    Hello,
    I'm new to PI BPM and have this scenario to implement.
    I'm supposed to delete all entries in a table and then insert data to the same table.
    Is BPM necessary? If it is, what is the best practice to implement my scenario?
    I want to make sure that all entries were successfully deleted before insert data.
    How do I check if all entries in the table were deleted successfully before
    initiating insert.
    Thank you.
    -Won

    Hi Won,
    Yes, this is possible without BPM.
    You have to create 2 separate mappings, each for deleting & inserting the records.
    You will have 2 different Interface mappings as well.
    But in ID, create a single interface determination.
    In that, configure Deletion interface mapping first and in the second row, configure Insertion interface mapping.
    Please make sure that the parameter 'Mainain Order At runtime' is checked in interface determination.
    -Supriya.

  • I right clicked my iPod on iTunes and clicked restore from back up because i thought it would undo my IOS6 update. IT DELETED ALL MY PICTURES (2,000) AND I DON'T KNOW HOW TO GET THEM BACK!!!! Please help me!!!!!

    I right clicked my iPod on iTunes and clicked restore from back up because i thought it would undo my IOS6 update. IT DELETED ALL MY PICTURES (2,000) AND I DON'T KNOW HOW TO GET THEM BACK!!!! Please help me!!!!!

    Well, if you have not backed them up, they are gone.
    Next time, when you have important material in only one place, back it up.

  • After recent upgrade to Yosemite on Macbook air bluetooth audio cuts out and associated video stops with audio. Likewise with airplay and Apple TV. I have deleted all my saved wifi connections and restarted numerous times. I do not expect a resolutio

    After recent upgrade to Yosemite on Macbook air bluetooth audio cuts out and associated video stops with audio. Likewise with airplay and Apple TV. I have deleted all my saved wifi connections and restarted numerous times. I do not expect a resolution from the community, but hope to get the attention of Apple engineers. If you are having same problems or have a miracle cure I am all ears.

    May start my own thread, but I'm having similar issues.
    I've been using an old iMac (running 10.7.5) and Apple TV for years with no issues. Last week I bought a new Macbook Pro running Yosemite and have had audio issues multiple times. The weird thing is that sometimes it works flawlessly, other times (like now) I spend half an hour just trying to get a song to play.
    My issues are: When I got to "computers" in Apple TV to stream my music, my music is sometimes chopper or intermittent, and I seen to know when it's going to happen based on the status wheel just before it plays. When I choose a song, the status wheel will spin for an unusually long time, usually an indicator that the audio is either not going to work, or stutter.
    When it does finally pull up a song, the playhead sits at the beginning of the song for a good 3-5 seconds before actually playing. Then, when it starts playing, it's all downhill. It will play a few seconds, drop out, play a few more seconds, drop out, and then ultimately the playhead will keep moving across the song as if it's playing, but there's no audio.
    Again, this is a new phenomenon never experienced by me. I've tried everything I could think of, some of them all at once:
    • restart Apple TV
    • restart Macbook Pro
    • quite iTunes/open
    • turn off Home Sharing on iTunes then reconnect it
    • unplugging and cycling both my modem and router
    None of these have alleviated the problem.
    The odd thing is, like this morning, the audio started up perfectly and never gave me any issues. It wasn't until later in the day that it started. Perhaps after the macbook pro had been put to sleep? Not sure.
    Regardless, this is an annoying trait, one that's new to me and my system (as stated, worked flawlessly until my new purchase), and is 100% limited to either a) the macbook pro b) Yosemite or c) both of them.

Maybe you are looking for