0

Error message:

The remote server returned an error: (401) Unauthorized.'

Code:

namespace SharepointUpload
{
    public partial class SharepointUpload : System.Windows.Forms.Form
    {
        public SharepointUpload()
        {
            InitializeComponent();
        }

        string path = "";
        string file = "";
        string fileName = "";

        private void pathBtn_Click(object sender, EventArgs e)
        {

            System.Net.WebRequest request = System.Net.HttpWebRequest.Create("http://schemas.microsoft.com/sharepoint/soap//_vti_bin/Copy.asmx");

            request.UseDefaultCredentials = true;

            request.PreAuthenticate = true;

            request.Credentials = CredentialCache.DefaultCredentials;

            System.Net.WebResponse response = request.GetResponse();

            openFileDialog1.FileName = String.Empty;
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                path = openFileDialog1.FileName;
                file = Path.GetFileName(openFileDialog1.FileName);
                fileName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
                //path = fileName;
                pathTxt.Text = path;
            }
        }

        private void uploadBtn_Click(object sender, EventArgs e)
        {

            System.Net.NetworkCredential credential = new System.Net.NetworkCredential(userTxt.Text, passTxt.Text, domainTxt.Text);
            //ClientContext client = new ClientContexthttps://sharepoint.domain.lan/path/to/service/") 
            ClientContext client = new ClientContext("http://sever/sites/Folder");
            client.RequestTimeout = 3600000;
            client.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(client_ExecutingWebRequtest);
            client.Credentials = credential;
            MemoryStream stream;
            using (FileStream fs = new FileStream(pathTxt.Text, FileMode.Open))
            {
                byte[] buffer = new byte[16 * 1024];
                byte[] byteArr;

                using (MemoryStream ms = new MemoryStream())
                {
                    int read;
                    while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                    byteArr = ms.ToArray();
                }

                stream = new MemoryStream(byteArr);

                var fi = new FileInfo(pathTxt.Text);
                //Project Administration presents root folder
                var list = client.Web.Lists.GetByTitle("Test");
                client.Load(list.RootFolder);
                client.ExecuteQuery();
                var fileUrl = list.RootFolder.ServerRelativeUrl + "/"+folderTxt.Text+"/" + fi.Name;
                client.RequestTimeout = Timeout.Infinite;
                try
                {
                    Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, stream, true);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Something went wrong: "+ex.ToString(), "Error...!", MessageBoxButtons.OK);
                    return;
                }
            }
            MessageBox.Show("Upload has completed...", "Information...", MessageBoxButtons.OK);

        }

        //this event is to prevent form based authentication. It uses windows instead.
        static void client_ExecutingWebRequtest(object sender, WebRequestEventArgs e)
        {
            e.WebRequestExecutor.WebRequest.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
        }

I would be most grateful for any assistance as I have tried solving this for weeks using different methods.

2 Answers 2

1

You must use SharePointOnlineCredentials instead of the NetworkCredential. Here is a sample:

using (ClientContext clientContext = new ClientContext("https://contoso.sharepoint.com/"))  
{  
    SecureString password = new SecureString();
    clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", password);
    Web web = clientContext.Web;
    clientContext.Load(web);
    clientContext.ExecuteQuery();
    Console.WriteLine(web.Title);
} 
0

Download SharePoint Online csom library and use SharePointOnlineCredentials class to pass credential, here is a code demo to upload file to Documents RootFolder:

 using (ClientContext cnx = new ClientContext("https://tenant.sharepoint.com/sites/dev"))
            {
                string password = "********";
                string account = "[email protected]";
                var secret = new SecureString();
                foreach (char c in password)
                {
                    secret.AppendChar(c);
                }
                cnx.Credentials = new SharePointOnlineCredentials(account, secret);

                Web web = cnx.Web;

                FileCreationInformation newFile = new FileCreationInformation();
                newFile.Content = System.IO.File.ReadAllBytes("c:\\test.jpg");

                //file url is name
                newFile.Url = @"test.jpg";
                List docs = web.Lists.GetByTitle("Documents");

                //get folder and add to that
                Folder folder = docs.RootFolder;
                File uploadFile = folder.Files.Add(newFile);

                cnx.Load(docs);
                cnx.Load(uploadFile);
                cnx.ExecuteQuery();
                Console.WriteLine("done");
            };

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.