Thursday, December 5, 2013

Move a source file and its properties from document library into a folder in same document library, delete the source and replace the destination file with another file

               using (SPSite oSite = new SPSite("http://Sharepoint2010:99/TestSite"))
                {
                    using (SPWeb oWeb = oSite.OpenWeb())
                    {
                                    //source file url
                                    string url = oWeb.Url + "/" + "SourceDocLib" + "/" + "SourceFileName";
                                   string fileName = "TestFile.docs"
                                    SPFile file = oWeb.GetFile(url);
                                    byte[] fileBytes = item.File.OpenBinary();

                         /destination document library
                          SPList docLib = oWeb.Lists.TryGetList("TestDocLib");
                          SPListItemCollection listItemCollection = docLib.Items;
                          string folderName = "TestFolder";
                          //get absolute destination Url
                          string folderUrl = oWeb.Url + "/" + docLib.Title + "/" + folderName + "/" + fileName;

                foreach (SPListItem listItem in listItemCollection)
                {
                    if (listItem["Name"] != null && listItem["Name"].ToString() == fileName)
                    {
                       // copy the source file and its properties to destination location
                        listItem.CopyTo(folderUrl);
                       //delete the source item
                        listItem.Delete();
                        break;
                    }
                }
                replace the destination file with another file
                SPFile destFile = oWeb.Files.Add(folderUrl, fileBytes, true);
                destFile.Update();

No comments:

Post a Comment