Search code examples
c#.netangularsharepoint-2010

Examples how to save file from external .Net application to Sharepoint


I need to save files from the existing AngularJS/.NET application to Sharepoint. Most of the examples I see online is when applications reside on Sharepoint itself. How do I save files from outside?

I've been given a user access to our organization's Sharepoint site but no application user passwords. What do I need to request from administrators of SharePoint site to be able to write the code?


Solution

  • We can use CSOM C# code to upload file to SharePoint 2010 document library. We need use an admin user and password to pass the Credentials in the .NET application server.

    public static void UploadFile(ClientContext context, string uploadFolderUrl, string uploadFilePath)
    {
        var fileCreationInfo = new FileCreationInformation
        {
            Content = System.IO.File.ReadAllBytes(uploadFilePath),
            Overwrite = true,
            Url = Path.GetFileName(uploadFilePath)
        };
        var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl);
        var uploadFile = targetFolder.Files.Add(fileCreationInfo);
        context.Load(uploadFile);
        context.ExecuteQuery();
    }
    

    Usage

    var siteUrl="http://sp2010";
    var username="admin";
    var password="xx";
    var domainName="domain1";
    using (var ctx = new ClientContext(webUri))
    {
        ctx.Credentials = new System.Net.NetworkCredential(username, password, domainName);
        UploadFile(ctx,"Documents/folder1",@"c:\upload\test.docx");
    }
    

    The following article for your reference.

    Uploading files using Client Object Model in SharePoint 2010