1

I have an asp.net web application that has a user select three files to upload. It then creates a random 6 digit folder on a SharePoint Online site and copy the three files into it.

It runs correctly locally in my VS2015, but when I run it in IIS8 on a Windows 2012 server, only the folder is created. I'm not sure if it's something in the code or an IIS setting.

Any tips/suggestions on how I could get this to work?

   protected void SaveFileToSharePoint(string fileName)
    {
        try
        {
            using (var context = new ClientContext(Url))
            {
                var passWord = new SecureString();
                foreach (var c in Password) passWord.AppendChar(c);
                context.Credentials = new SharePointOnlineCredentials(UserName, passWord);
                var web = context.Web;

                var newFile = new FileCreationInformation { Content = System.IO.File.ReadAllBytes(fileName), Url = Path.GetFileName(fileName) };
                var docs = web.Lists.GetByTitle("Documents");
                Microsoft.SharePoint.Client.Folder folder = docs.RootFolder.Folders.GetByUrl(NewFolder);
                Microsoft.SharePoint.Client.File uploadFile = folder.Files.Add(newFile);

                context.Load(docs);
                context.Load(uploadFile);
                context.ExecuteQuery();
            }
        }
        catch (Exception ex)
        {

        }
    }

    protected void Button1_OnClick(object Source, EventArgs e)
    {
        try
        {
            if (getFile1.PostedFile != null && getFile2.PostedFile != null && getFile3.PostedFile != null)
            {
                using (var context = new ClientContext(Url))
                {
                    Random generator = new Random();
                    NewFolder = generator.Next(0, 999999).ToString("D6");
                    CreateFolder(NewFolder);

                    SaveFileToSharePoint(getFile1.Value.ToString());
                    SaveFileToSharePoint(getFile2.Value.ToString());
                    SaveFileToSharePoint(getFile3.Value.ToString());
                    Session["num"] = NewFolder.ToString();
                    Response.Redirect("ThankYouPage.aspx");
                }
            }
            else
            {
            }
        }
        catch (Exception ex)
        {
        }
    }

    protected void CreateFolder(string FolderName)
    {
        using (var clientContext = new ClientContext(Url))
        {
            var passWord = new SecureString();
            foreach (var c in Password) passWord.AppendChar(c);
            clientContext.Credentials = new SharePointOnlineCredentials(UserName, passWord);
            var web = clientContext.Web;

            var list = clientContext.Web.Lists.GetByTitle("Documents");
            list.EnableFolderCreation = true;

            clientContext.Load(list);
            clientContext.Load(list.RootFolder);
            clientContext.Load(list.RootFolder.Folders);
            clientContext.ExecuteQuery();

            var folderCollection = list.RootFolder.Folders;

            foreach (var folder in folderCollection)
            {
                if (folder.Name == FolderName)
                {
                    clientContext.Load(folder.Files);
                    clientContext.ExecuteQuery();
                }
                else
                {
                    var itemCreateInfo = new ListItemCreationInformation
                    {
                        UnderlyingObjectType = FileSystemObjectType.Folder,
                        LeafName = FolderName
                    };

                    var newItem = list.AddItem(itemCreateInfo);
                    newItem["Title"] = FolderName;
                    newItem.Update();
                    clientContext.ExecuteQuery();

                    break;
                }
            }
        }
    }

2 Answers 2

0

You need to remember that this is back end web server code, and it runs on the server. So that System.IO.File.ReadAllBytes call is looking on the server's file system for a file which isn't there.

Web servers work by receiving, processing, and serving HTTP requests and responses. There's no way a server can look inside your computer, and that's a good thing, or else web sites could just pull arbitrary files off anyone's computers.

You're going to have to find a different solution for uploading files to a web server. Web Forms had a FileUpload control. In MVC you render an input with type of "file" inside a form and handle the upload in your POST action. You might need to do a bit more Googling for your specific web technology.

Also - you have an empty catch block, which essentially swallowed your exception. If you had just let the exception be thrown you'd have found your error right away. Exceptions are your friends - they tell you when things are going wrong. Do not swallow them.

0

We can use AjaxFileUpload control to upload multiple files to SharePoint.

The code below for your reference.

protected void OnUploadComplete(object sender, AjaxFileUploadEventArgs e)  
{  
    try  
    {  
        //gets the filename  
        string fileName = Path.GetFileName(e.FileName);  
        //gets the temporary location of file and ID of folder where files are stored in temporary folder  
        string path = Path.Combine(Path.GetTempPath(), "_AjaxFileUpload", e.FileId);  
        //store the path in Sessio  
        Session["FileDirectory"] = path;  
        //get the site
        var siteUrl="";
        var Password="";
        var UserName="";
        ClientContext context = new ClientContext(siteUrl);  
        var passWord = new SecureString();
        foreach (var c in Password) passWord.AppendChar(c);
        context.Credentials = new SharePointOnlineCredentials(UserName, passWord);
        //get the web object  
        Web oWebsite = context.Web;  
        context.Load(oWebsite);
        //execute the web object  
        context.ExecuteQuery();  
        //get the current list  
        List CurrentList = context.Web.Lists.GetByTitle(listName);  
        context.Load(CurrentList.RootFolder);  
        context.ExecuteQuery();
        String fileURL = (path + "\\" + fileName);
        using(FileStreamfileStream = new FileStream(fileURL, FileMode.Open))  
        Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, CurrentList.RootFolder.ServerRelativeUrl.ToString() + "/" + e.FileName, fileStream, true);  
    }  
    catch (Exception ex)  
    {  
        lblError.Text = ex.ToString();  
        lblError.BackColor = System.Drawing.Color.Red;  
        lblError.ForeColor = System.Drawing.Color.White;  
    }  
    finally  
    {  
        //delete files from temp folder  
        e.DeleteTemporaryData();  
    }  
}  

Reference: Uploading Multiple Files to SharePoint Document Library using .NET CSOM

Your Answer

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

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