0

I have created two doc libraries(source and destination),in source library files are there,am moving those files to destination library,upto here working fine. My problem is how to append source doc library permissions to destination doc library.(for ex source library am given readonly permission,i want to apply same permission to destination library also) Am using bellow code to move docs from source doc to destination doc and i want copy/move permissions also. Does somebody have an answer to this?Below one is i wrtten

public partial class Test : LayoutsPageBase
{
    //protected void Page_Load(object sender, EventArgs e)
    //{
    //}
    protected Label LabelItems;
    protected TextBox TextDestination;
    protected System.Collections.Generic.List<SPListItem> ListItems;
    protected override void OnLoad(EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                if (Request.QueryString["items"] != null && Request.QueryString["source"] != null)
                {

                    string source = Request.QueryString["source"];
                    if (Request.QueryString["items"].ToString() != "")
                    {
                        string[] items = Request.QueryString["items"].ToString().Split('|');

                        lblerror.Text = "You have selected the following items to move:<br><br>";
                        lblerror.Visible = true;
                        source = source.Substring(1, source.Length - 2).ToLower();

                        Guid sourceID = new Guid(source);
                        SPDocumentLibrary sourceDocLib = (SPDocumentLibrary)SPContext.Current.Web.Lists[sourceID];
                        //ViewState["Source"] = sourceDocLib;
                        ListItems = new System.Collections.Generic.List<SPListItem>();
                        for (int i = 1; i < items.Length; i++)
                        {
                            SPListItem currentListItem = sourceDocLib.GetItemById(int.Parse(items[i]));
                            ListItems.Add(currentListItem);
                            lblerror.Text += currentListItem.Name + "<br>";
                        }
                    }
                    else
                    {
                        lblerror.Text = "You have not selected any document";
                        lblerror.Visible = true;
                    }
                }
            }
            catch (Exception ex)
            {
                lblerror.Text += "Error : " + ex.Message;
                lblerror.Visible = true;
            }
        }

    }

    protected void btnOK_Click(object sender, EventArgs e)
    {
        try
        {
            string source = Request.QueryString["source"];
            if (Request.QueryString["items"].ToString() != "")
            {
                string[] items = Request.QueryString["items"].ToString().Split('|');
                lblerror.Text = "You have selected the following items to move:<br><br>";
                lblerror.Visible = true;
                source = source.Substring(1, source.Length - 2).ToLower();
            Guid sourceID = new Guid(source);
            //lblerror.Text = txtDestination.Value; //hdnfldurl.Value;

          //  SPDocumentLibrary sourceDocLib = (SPDocumentLibrary)SPContext.Current.Web.Lists[source];
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList sourceDocLib =web.Lists[sourceID];
                    SPQuery spquery = new SPQuery();
                    spquery.Query = @"<Where><In><FieldRef Name='ID' /><Values>";
                    foreach (var id in items)
                    {if(id!="")
 spquery.Query +="<Value Type='Counter'>"+id+"</Value>";

                    }
                  spquery.Query +=  "</Values></In></Where>";

                  SPListItemCollection listItems = sourceDocLib.GetItems(spquery);
                  if (listItems.Count > 0)
                  {
                      for (int i = listItems.Count - 1; i >= 0; i--)
                      {
                          listItems[i].File.CopyTo(txtDestination.Value +"/"+ listItems[i].File.Name, true);
                          lblerror.Text = txtDestination.Value;
                          //SPQuery a = new SPQuery();
                          //a.Query=


                          //    SPListItem items=.getite()

                          //SPSecurity.RunWithElevatedPrivileges(delegate()
                          //{
                          //    txtDestination.SystemUpdate();
                          //    if (listItems[i].HasUniqueRoleAssignments)
                          //    {
                          //        //Break target document inheritance and do not copy the parent permissions.
                          //        TargetDoc.BreakRoleInheritance(false);
                          //        //copying all the permission from source item to target item
                          //        foreach (SPRoleAssignment role in listItems[i].RoleAssignments)
                          //        {
                          //            TargetDoc.RoleAssignments.Add(role);
                          //        }
                          //        TargetDoc.SystemUpdate(false);
                          //    }
                          //});

                          //listItems[i].File.Delete();
                      }
                  }
                }
                }
            }
        }
        catch (Exception ex)
        {
            lblerror.Text = ex.Message;
        }

    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        //string redirectURL = string.Format("{0}/{1}", SPContext.Current.Web.Url, "/sites/Reimbursement/");
        //Lit.Text = "<script type='text/javascript'>window.location = '" + redirectURL + "/';</script>";
    }
    // more stuff here, omitted for simplicity
}
}

Second class:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace MoveTo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://serverName:1111/SitePages/Home.aspx"))
            {
                using (SPWeb web = site.RootWeb)
                {
                    SPFileCollection collFile = web.GetFolder("Shared Documents").Files;
                    int count = collFile.Count;
                    while (count != 0)
                    {
                        collFile[count - 1].MoveTo("Destination Library/" + collFile[count - 1].Name, true);
                        count--;
                    }
                }
            }
        }
    }
}`
3
  • How are you doing the copying of files? Did you write some server side code, workflows or something else?
    – Unnie
    Jul 22, 2015 at 7:47
  • i write some code
    – chakri
    Jul 22, 2015 at 7:53
  • 1
    If you would paste your code and describe where you're executing it, we would be able to help you. But without knowing if its SSOM, CSOM, JSOM, inside an event receiver, timerjob ... it's impossible to give you more specific answers than you already got.
    – Andreas
    Jul 22, 2015 at 11:23

1 Answer 1

0

If you are using File.MoveTo it will also copy the permissions of the individual files over to the target file, if there is item level permission.See below code which copies over the permission of the library:

 static void Main(string[] args)
    {
        using (SPSite site = new SPSite("http://serverName:1111/SitePages/Home.aspx"))
        {
            using (SPWeb web = site.OpenWeb())
            {

                foreach (SPListTemplate temp in web.ListTemplates)
                {
                    Console.WriteLine(temp.Name);
                }

                SPList targetList = web.Lists.TryGetList("Destination Library");
                SPList sourceList = web.Lists.TryGetList("Shared Documents");
                if (sourceList.HasUniqueRoleAssignments)
                    CopyListPermissions(sourceList, targetList);
                SPFileCollection collFile = sourceList.RootFolder.Files;

                for (int i = collFile.Count - 1; i >= 0; i--)
                {
                    SPFile file = collFile[i];
                    string targetFileurl = string.Concat(targetList.RootFolder.Url, "/", file.Name);
                    file.MoveTo(targetFileurl, SPMoveOperations.Overwrite, true);
                }
            }
        }
    }

    private static void CopyListPermissions(SPList sourceList, SPList targetList)
    {
        SPSecurity.RunWithElevatedPrivileges(delegate()
      {
          targetList.BreakRoleInheritance(false);
          foreach (SPRoleAssignment role in sourceList.RoleAssignments)
          {
              targetList.RoleAssignments.Add(role);
          }
          targetList.Update(false);
      });
    }
9
  • Please send me full code
    – chakri
    Jul 22, 2015 at 10:45
  • hi Unnie plz send me full code
    – chakri
    Jul 23, 2015 at 5:48
  • edited the answer
    – Unnie
    Jul 23, 2015 at 8:57
  • Thank You Unnie i posted my total code in top what am written,for that code how to add permissions.
    – chakri
    Jul 23, 2015 at 9:49
  • Just follow the code written on top, just change the source , destination library name and the site url
    – Unnie
    Jul 23, 2015 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.