Saturday, 18 February 2012

Transfer document from one library to another


 SPSecurity.RunWithElevatedPrivileges(delegate()
                                    {
                                        using (SPSite osite = new SPSite("http://admin-pc:2345"))
                                        {
                                            try
                                            {
                                                using (SPWeb oweb = osite.OpenWeb("subsite"))
                                                {
                                                    SPDocumentLibrary olist = (SPDocumentLibrary)oweb.Lists.TryGetList("Shared Documents");
                                                    using (SPWeb newweb = osite.RootWeb)
                                                    {
                                                        SPDocumentLibrary olistnew = (SPDocumentLibrary)newweb.Lists.TryGetList("Shared Documents");
                                                        int count = olistnew.Items.Count;
                                                        int i;

                                                        for (i = 0; i < count; i++)
                                                        {

                                                            oweb.AllowUnsafeUpdates = true;
                                                            SPListItem oitemnew = olistnew.Items[i];
                                                            byte[] fileBytes = oitemnew.File.OpenBinary();
                                                            string desturl = olist.RootFolder.Url + "/" + oitemnew.File.Name;
                                                            SPFile librarynew = olist.RootFolder.Files.Add(desturl, fileBytes, true);
                                                            librarynew.Update();
                                                            oweb.AllowUnsafeUpdates = false;

                                                        }
                                                        Console.WriteLine("Document transfered");
                                                        Console.ReadLine();

                                                    }
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                throw ex;
                                            }
                                        }
                                    });
        }

No comments:

Post a Comment