I'm trying to get the basics down on connecting to SharePoint Online (as opposed to an on-prem SharePoint) using C# in my Unity application. Below is the code I am using as a starting point (more handling/security to be involved later). What is mind-blowing is that this code will work if I have Fiddler running (a web-activity snooper tool) or if I compile it outside of Unity. Without Fiddler (and in Unity), I get the error: SocketException: No connection could be made because the target machine actively refused it.
What could Fiddler possibly be doing to make this work, and is there a way I can duplicate it in my code?
public void SharepointLogin()
{
//string url = "https://<private_server>/sites/sitename";
string url = "https://<company>.sharepoint.com/sites/otherSiteName";
//string folderpath = "/sites/sitename/folder/";
string folderpath = "/sites/otherSiteName/folder/";
string filepath = "W:/ServerData.csv";
using (var ctx = new ClientContext(url))
{
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
SecureString ss = new NetworkCredential("", password).SecurePassword;
//ctx.Credentials = new System.Net.NetworkCredential(username, password);
ctx.Credentials = new SharePointOnlineCredentials(usernameWithDomain, ss);
var filename = Path.GetFileName(filepath);
using (FileStream fs = new FileStream(filepath, FileMode.Open))
{
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, folderpath + filename, fs, true);
}
}
}
Additional info:
Semi-related but maybe insightful, Unity seems to have trouble using CredentialCache.DefaultNetworkCredentials
(it actually appears not to include it at all) when connecting to an "on-prem" SharePoint site which forces me to re-create them with System.Net.NetworkCredentials
instead. (see commented lines which DOES work for the other site). If I build that same code outside Unity, it also works fine so clearly Unity is stripping it for some reason. Unity also seems to have an issue with our proxy in general, but since I can get through with the on-prem server, I'm hoping there's also a way to get through to the SharePoint Online server--especially since Fiddler somehow makes it work and thus Unity must not simply be stripping the credentials like it did with DefaultCredentials.
SharePoint Online requires a SharePointOnlineCredentials object specifically so I don't get the same workaround as with on-prem. Fiddler did not fix the on-prem connection, however, when using DefaultNetworkCredentials like it seems to when using the SharePointOnlineCredentials, so clearly it's a different failure mechanism. I've also read through https://www.telerik.com/blogs/help!-running-fiddler-fixes-my-app- but it does not appear to provide my answer.