0

i need to navigate to an 'upload' folder in the documents folder in code. I can connect to the site ok but not sure how to navigate to that folder. I am attempting to use clientContext.Web.Lists.GetByTitle("Uploads"); it does resolve but not sure if its successful as when i attempt the upload i get an authorisation exception even though earlier on i am using the same credentials to get the web title. The account i am connecting with is a site owner. I suspect i am getting the error as i am not on the folder i want to be.. not sire if there is a way of checking that?

All suggestions welcome :)

Andy

1 Answer 1

0

To get into the specific folder we need to use the "GetFolderByServerRelativeUrl" like below:

Folder folder = ctx.Web.GetFolderByServerRelativeUrl("Shared Documents");

Sample upload code:

ClientContext ctx = new ClientContext("http://sp13");

Folder folder = ctx.Web.GetFolderByServerRelativeUrl("Shared Documents");
string file = String.Concat(Environment.CurrentDirectory, @"\Files\SharePointGuidance2010.pdf");

List docLib = ctx.Web.Lists.GetByTitle("Documents");
ctx.Load(docLib);
ctx.ExecuteQuery();

using (MemoryStream stream = new MemoryStream( System.IO.File.ReadAllBytes(file) ) )
{
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, "/shared documents/SubFolder/spg.pdf", stream, true);
}

Example to get specific folder:

   string folderName = "/MyLibrary/Upload(Folder)"; 
   Web web = context.Web;
   List docLib = context.Web.Lists.GetByTitle("MyLibrary");
   Folder folder = web.GetFolderByServerRelativeUrl(folderName);                

   ctx.Load(context.Web);
   ctx.Load(docLib);
   ctx.Load(folder);               
   ctx.ExecuteQuery();

You may refer the below thread where it has been discussed the similar question:

Upload files to a specific folder in a Library on Sharepoint

9
  • Thanks! if i have a folder 'Uploads' in my 'Documents' folder would the path be "/shared documents/uploads/filename.xxx'?
    – ink169
    Mar 19, 2020 at 14:01
  • I don't see the folder variable being used in the logic?
    – ink169
    Mar 19, 2020 at 14:10
  • Updated the answer to get the specific folder
    – SP 2022
    Mar 19, 2020 at 14:27
  • all working, thanks a lot Habibur :)
    – ink169
    Mar 19, 2020 at 15:03
  • Now.. does the context contain the guid or string for me to link to the document ? is there a way to get that?
    – ink169
    Mar 19, 2020 at 15:04

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.