Monday, March 13, 2017

C# - Client Object model to Delete the file, upload file , Check in and Publish it in to sharepoint Document library

 

 

    string FileName = Path.GetFileName(“FileLocation”");
    string docLibName = "Site Collection Documents";
    string spPath = siteUrl + "/SiteCollectionDocuments/SaleRanking.xlsx";

    // get the server relative URL
    Uri filename = new Uri(@spPath);
    string server = filename.AbsoluteUri.Replace(filename.AbsolutePath, "");
    string serverrelative = filename.AbsolutePath;

    try
    {      
            Microsoft.SharePoint.Client.File f = null;
            SP.ClientContext ctx = new SP.ClientContext(siteUrl);
            Web web = ctx.Web;
            List docs = web.Lists.GetByTitle(docLibName);
            f = web.GetFileByServerRelativeUrl(serverrelative);
            ctx.Load(f);
            f.DeleteObject();ctx.ExecuteQuery(); // Delete file here but throw Exception       
            ctx.ExecuteQuery(); // Delete file here but throw Exception
           
            FileCreationInformation newFile = new FileCreationInformation();
            newFile.Content = System.IO.File.ReadAllBytes(@FileLocation);
            newFile.Url = spPath;
            Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
            ctx.Load(uploadFile);
            ctx.ExecuteQuery(); // Add new file here    

            f.CheckIn(string.Empty, CheckinType.MajorCheckIn);  // Check in File
            ctx.ExecuteQuery(); // Check in File             

             f.Publish("file published");
             ctx.ExecuteQuery(); // Publish File 

      }catch (Exception ex)   {
      }

No comments:

Post a Comment