简体   繁体   中英

How to implement SharePoint File Upload functionality in C# using this code?

I am trying to add SharePoint File Upload functionality to my C# MVC project.

The following is my code:

        var sourceFilePath = @"Z:\itworked.txt";
        var targetUrl = "/Project Room Test";

        using (var ctx = new ClientContext("https://company.sharepoint.com/sites/ProjectRoom"))
        {
            SecureString passWord = new SecureString();

            foreach (char c in "ThisIsNotMyPWD123".ToCharArray()) passWord.AppendChar(c);

            ctx.Credentials = new SharePointOnlineCredentials("username@company.com", passWord);

            //Upload file
            var targetFileUrl = String.Format("{0}/{1}", targetUrl, Path.GetFileName(sourceFilePath));

            using (var fs = new FileStream(sourceFilePath, FileMode.Open))
            {
                Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, targetFileUrl, fs, true);
            }
        }

I know that the 1st line of code works because if I change it by removing the file extension (.txt), I receive an error message that the file cannot be found.

I know that lines 4-10 work because I was able to perform a test where I grab the web.Title and set it equal to a Notes field in an application form. This operation needs my credentials.

The error that is produced is 401 Unauthorized against line 17 => Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, targetFileUrl, fs, true);

I believe that the issue is the targetUrl and/or targetFileUrl.

The following is the URL of the location where I can drag and drop files: https://company.sharepoint.com/sites/ProjectRoom/Project%20Room%20Test/Forms/AllItems.aspx

If I drag and drop a file and then copy its link, the following is the result: https://company.sharepoint.com/:t:/r/sites/ProjectRoom/Project%20Room%20Test/itworked.txt?btg=2&web=2&e=7kesiF

The solution was to update the targetUrl => var targetUrl = /sites/ProjectRoom/Project Room Test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM