0

I would like to help me with this task if it is possible. I would like to be able to upload files to folders on Sharepoint Online. At the moment, I can only upload to libraries. Below is the code that I am currently using.

private void BtnUpload_Click(object sender, EventArgs e)
{
    siteURL += "/" + tbDept.Text;

    try
    {
        using (ClientContext ctx = new ClientContext(siteURL))
        {
            SecureString passWord = new SecureString();
            foreach (var c in logUser.getPassword())
            {
                passWord.AppendChar(c);
            }
            ctx.Credentials = new SharePointOnlineCredentials(logUser.getUsername(), passWord);
            Web web = ctx.Web;

            foreach (string fname in arrAllFiles)   //arrAllFiles --> contains multiple files to be uploaded
            {
                FileCreationInformation newFile = new FileCreationInformation();
                newFile.Overwrite = true;
                newFile.Content = System.IO.File.ReadAllBytes(fname);
                newFile.Url = System.IO.Path.GetFileName(fname);
                List docs = web.Lists.GetByTitle(tbLibrary.Text); //tbLibrary --> Library's Name
                Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
                ctx.ExecuteQuery();
            }
            MessageBox.Show("Upload Complete!");
            siteURL = "https://mycompany.sharepoint.com";
        }
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
        siteURL = "https://mycompany.sharepoint.com";
    }
}

The code is working fine. I just need to add functionality in order to upload files to a specific folder in a library.

Thank you in advance.

I.Sno5
  • 23
  • 1
  • 1
  • 3
  • will this be done using a windows app or web app.. if it's via web application then you need to understand `ServerMapPath` function take a look at this link for example https://stackoverflow.com/questions/1199486/server-mappath-in-c-sharp-classlibrary – MethodMan Nov 30 '17 at 16:29
  • It is gonna be windows app. – I.Sno5 Nov 30 '17 at 16:34
  • then get the location of the newworkshare it would look something like this `'\\mySharePointPath\somefolder\"` you will need to get with your network team to make the folder location fully read-write accessible and I would suggest creating your own little `async CoyToShairPoint` function too using the standard C#.NET CopyTo function just decorate it appropriately using asych Task and await functions.. – MethodMan Nov 30 '17 at 16:37
  • And this is where I have got problem. At the moment I have got something like: URL--> "https://mycompany.sharepoint.com/rep/" Library--> "UK" Where am I supposed to put the folder name? – I.Sno5 Nov 30 '17 at 16:43
  • ok if you are doing this via web interface currently , you need to know the virtual folder location.. if you are doing it thru code you need the ip address of the url or you need the `UNC path` please get with your network team as I do not know the current structure of your internal network. also you stated it will be a windows app.. File location in Web sites or url's are different than file paths in windows system, I would suggest you do some googling and trying to understand the difference. – MethodMan Nov 30 '17 at 16:46
  • I appreciate your help. The thing is that I can currently upload to a Library without having any problems using the Sharepoint Client methods. I mean there must be something that can upload to a folder in s Library. – I.Sno5 Nov 30 '17 at 16:52
  • yeah are you uploading it via a web application ? if that current code uploads correctly, then once again you need to have a folder on their web server created and have permissions granted in order to upload to your folder that you want to create.. please clarify what the code above in your question is from.. – MethodMan Nov 30 '17 at 16:57
  • The code above it gonna part of a windows form application. I have got full permission to that folder. There is no issue with the code I just want to know if there is any parameter that I can add in order to upload to a folder within a Library. What I am doing right now is to choose in which library I want to upload (and it is fine) now I want to point in which specific folder in that library I want to upload. – I.Sno5 Nov 30 '17 at 17:14
  • @I.Sno5 I edited my answer, my code works for sure, check it out and see if it helps. – Abbas Dec 01 '17 at 14:57

2 Answers2

3

UPDATE: Following code works, I tested it myself:

var filePath = @"C:\PATH_TO_FILE\test.docx";

using (var context = new ClientContext("YOUR_SITE_URL") { Credentials = credentials })
{
    var folder = context.Web.GetFolderByServerRelativeUrl("/sites/YOUR_SITE/LIBRARY_INTERNAL_NAME/FOLDER_NAME");

    context.Load(folder);
    context.ExecuteQuery();

    folder.Files.Add(new FileCreationInformation
    {
        Overwrite = true,
        Content = System.IO.File.ReadAllBytes(filePath),
        Url = Path.GetFileName(filePath)
    });

    context.ExecuteQuery();
}
Abbas
  • 14,186
  • 6
  • 41
  • 72
1

Here's some sample code that I wrote a while back. You can tweak it to your needs. The SaveBinaryDirect method takes the context and the relative path which includes the folder. That should work.

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);
}

or Try the following edits to your code:

Folder folder = web.GetFolderByServerRelativeUrl("Documents/Subfolder");
FileCreationInformation fci = new FileCreationInformation();
fci.Content = System.IO.File.ReadAllBytes(@”..\..\myfile.txt”);
fci.Url = “myfile.txt”;
fci.Overwrite = true;
File fileToUpload = folder.Files.Add(fci);
ctx.Load(fileToUpload);

ctx.ExecuteQuery();
Jason Rivera
  • 236
  • 2
  • 8
  • Thanks for your answer but i am getting a File Not Found Exception (from the sharepoint end) at this point: ctx.ExecuteQuery(); – I.Sno5 Dec 01 '17 at 13:01
  • I edited my answer with an additional option. I've used the one first option but maybe not with a folder but that should work. Option 2 is to get the folder itself and to create a File Creation Information object from your file and load that. – Jason Rivera Dec 01 '17 at 14:25
  • Thanks man. You are legend! The updated code is working very well. – I.Sno5 Dec 01 '17 at 15:32
  • oooh, a legend? That's a first... I'll take it :) Glad I could help. – Jason Rivera Dec 01 '17 at 15:33