#region Using Directives using System; using System.IO; using System.Linq; using SP = Microsoft.SharePoint.Client; using System.Net; #endregion namespace SharePointClient { class Program { static void Main(string[] args) { string srcUrl = "https://aaa/bbb/ccc/"; string destUrl = "https://aaa/bbb/ddd/";; System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("aaa", "ccc", "vvvv"); string srcLibrary = "MySrc Library"; string destLibrary = "MyDest Library"; //copy latest full version of file CopyDocuments(srcUrl, destUrl, srcLibrary, destLibrary, credentials); } #region Supporting Methods public static void CopyDocuments(string srcUrl, string destUrl, string srcLibrary, string destLibrary, System.Net.NetworkCredential credentials) { // set up the src client using (SP.ClientContext srcContext = new SP.ClientContext(srcUrl)) { // set up the destination using (SP.ClientContext destContext = new SP.ClientContext(destUrl)) { srcContext.Credentials = credentials; destContext.Credentials = credentials; // get the source web SP.Web srcWeb = srcContext.Web; SP.List srcList = srcWeb.Lists.GetByTitle(srcLibrary); // SP.CamlQuery query = SP.CamlQuery.CreateAllItemsQuery(5); // SP.CamlQuery query = new SP.CamlQuery(); query.ViewXml = @"<View><Query><Where><Eq><FieldRef Name='ICD_x0020_ID' /><Value Type='Text'>6382</Value></Eq></Where></Query></View>"; SP.ListItemCollection srcItems = srcList.GetItems(query); srcContext.Load(srcItems); srcContext.ExecuteQuery(); // get the destination web SP.Web destWeb = destContext.Web; destContext.Load(destWeb); destContext.ExecuteQuery(); foreach (var item in srcItems) { try { if (item.FileSystemObjectType == SP.FileSystemObjectType.File) { // get the first file version SP.File file = item.File; SP.FileVersionCollection versions = file.Versions; srcContext.Load(versions); srcContext.ExecuteQuery(); //SP.FileVersion firstVersion = versions.OrderBy(L => L.ID).FirstOrDefault(); SP.FileVersion firstVersion = versions.OrderBy(L => L.ID).Last(); // foreach (SP.FileVersion _version in versions) { Console.WriteLine("Version :{0}\t", _version.VersionLabel); } // if (destContext.HasPendingRequest) destContext.ExecuteQuery(); string filePath = Path.Combine(@srcUrl, firstVersion.Url).Replace(" ", "%20"); string fileName = Path.GetFileName(filePath); // build new location url string nLocation = destWeb.ServerRelativeUrl.TrimEnd('/') + "/" + destLibrary.Replace(" ", "%20") + "/" + fileName; WebClient client = new System.Net.WebClient(); client.Credentials = credentials; using (Stream fileRef = client.OpenRead(filePath)) { SP.File.SaveBinaryDirect(destContext, nLocation, fileRef, true); } } } catch (Exception ex) { Console.WriteLine("File Error = " + ex.ToString()); } } } } } #endregion } }