I'm new to Sharepoint. Is it possible to upload files to an aspx page using c# and .NET Framework 4.7? The site I'm trying to upload to is "https://myorg.sharepoint.com/sites/SPODemo/Test%20Upload/Forms/AllItems.aspx" but any sample code I've seen uses a standard url rather than an aspx page. The SP admin person created this site for us in SP so all I have is the aspx page.
I've tried several variations of "https://myorg.sharepoint.com/sites/SPODemo/Test%20Upload/Forms" as the url to upload to but I continually get a 401 Unauthorized error. The logon id I'm using is the one I use to log on to our company network, which has been give the correct privileges to create files on the aspx page (I can upload files to the SP site via a browser).
I've tried variations of the code below but always get a 401 error:
private void WriteFileToSharepoint(string fileName)
{
string siteUrl = "https://myorg.sharepoint.com/sites/SPODemo";
var login = "[email protected]";
var password = "my_windows_pw";
var documentLibrary = "Test%20Upload";
//var folderUrl = "/sites/SPODemo/" + documentLibrary + "/Forms";
var folderUrl = "/sites/SPODemo/" + documentLibrary;
try
{
using (var stream = new MemoryStream())
{
FileStream fileStream = System.IO.File.OpenRead(fileName);
string source_filename = Path.GetFileName(fileName);
FileCreationInformation fci = new FileCreationInformation
{
Overwrite = false,
Url = source_filename,
ContentStream = fileStream
};
using (var ctx = new ClientContext(siteUrl))
{
var securePassword = new SecureString();
foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
NetworkCredential _myCredentials = new NetworkCredential(login, password, "myorg");
ctx.Credentials = _myCredentials;
var targetFileUrl = String.Format("{0}/{1}", folderUrl, fci.Url);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, targetFileUrl, fci.ContentStream, true);
}
// Also tried ctx.Load(targetFileUrl) then ctx.ExecuteQuery();
}
}
catch (Exception ex)
{
throw;
}
}
The error messages I get:
- Cannot contact web site 'https://myorg.sharepoint.com/' or the web site does not support SharePoint Online credentials. The response status code is 'Unauthorized'.
- Access denied. Before opening files in this location you must first browse to the web site and select the option to login automatically.
Thanks in advance.