SharePoint Online – Browse folder from PC and upload to SharePoint Document library

Hello everybody,

Recently I got an opportunity to work on browse functionality using windows forms application.

The functionality is to select a folder from PC and upload the folder with files in it to SharePoint document library. Let’s get started!

Prerequisites:

  1. SharePoint Online Tenant.
  2. Simple window form application with only one button control on it to browse in Visual Studio IDE.

Scenario:

  1. Name of folder to be uploaded – Test Folder.
  2. Hierarchy of folder
FolderHierarchy
Figure .1 Folder Hierarchy

Let’s see how code works:

  1. When browse button is clicked, it opens “Browse for Folder” dialog to select and upload folder from.
FolderUpload
Figure .2 Browse folders to upload
  1. Select the source folder (Test Folder) from drive and click OK.
FolderBrowse
Figure .3 Select folder to upload
  1. As soon as OK button is clicked, code will perform its first step to connect to SharePoint site with the site url and credentials provided in app.config file.
  2. Detailed comments are provided in the code to make it easy to understand and self explanatory.
  3. Detailed code is given below.

Code:

App.Config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<appSettings>
<add key="SiteURL" value="Provide SP site collection url here"/>
<add key="Username" value="Provide your username here"/>
<add key="Password" value="Provide your password here"/>
</appSettings>
</configuration>

Form1.cs

using Microsoft.SharePoint.Client;
using System;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Security;
using System.Windows.Forms;

namespace BrowseAndUploadFiles
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
this.buttonBrowse.Click += new System.EventHandler(this.buttonBrowse_Click);
}

///
/// Browse button click event handler - When clicked it opens browse files dialog to select folder to upload.
///

//////private void buttonBrowse_Click(object sender, EventArgs e)
{
try
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.ShowNewFolderButton = true;
DialogResult result = folderDialog.ShowDialog();
if (result == DialogResult.OK)
{
//textBoxFilename.Text = folderDialog.SelectedPath; //This step is not mandatory
string filename = folderDialog.SelectedPath;
Environment.SpecialFolder root = folderDialog.RootFolder;

#region Code to Connect to SharePoint site

//Read details from app.config file
string siteURL = ConfigurationManager.AppSettings["SiteURL"];
string userName = ConfigurationManager.AppSettings["UserName"];
string password = ConfigurationManager.AppSettings["Password"];

ClientContext clientContext = new ClientContext(siteURL);
SecureString securePassword = new SecureString();

//Formation of secure password string
foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);

clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);

//Load the web
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();

#endregion

//Call to the method which uploads folders recursively to Documents library on SharePoint site
UploadFoldersRecursively(clientContext, filename, "Documents");

MessageBox.Show("File upload complete", "buttonBrowse_Click", MessageBoxButtons.OK, MessageBoxIcon.Information);
}//if (result == DialogResult.OK)
}//try
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}//buttonBrowse_Click()

#region UploadFoldersRecursively
///
/// Method to upload folder - Selected folder on PC gets created on SP site in Document library
///

/////////public static void UploadFoldersRecursively(ClientContext clientContext, string sourceFolder, string destinationLibraryTitle)
{
try
{
//Load detination library
Web web = clientContext.Web;
var query = clientContext.LoadQuery(web.Lists.Where(p =&amp;amp;gt; p.Title == destinationLibraryTitle));
clientContext.ExecuteQuery();
List documentsLibrary = query.FirstOrDefault();
var folder = documentsLibrary.RootFolder;
DirectoryInfo dir = new DirectoryInfo(sourceFolder);

clientContext.Load(documentsLibrary.RootFolder);
clientContext.ExecuteQuery();

folder = documentsLibrary.RootFolder.Folders.Add(dir.Name);
clientContext.ExecuteQuery();

UploadFolder(clientContext, dir, folder);
}//try
catch(Exception ex)
{
MessageBox.Show(ex.Message, "UploadFoldersRecursively", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}//public static void UploadFoldersRecursively(ClientContext clientContext, string sourceFolder, string destinationLibraryTitle)
#endregion

#region UploadFolder
///
/// Method to upload a folder - Uploads folder recursively that means if selected folder to upload contains more folders
/// in it then it uploads each and every folder and files under every folder to sharepoint site
///

/////////public static void UploadFolder(ClientContext clientContext, System.IO.DirectoryInfo folderInfo, Folder folder)
{
FileInfo[] files = null;
DirectoryInfo[] subDirs = null;

try
{
//Get all files from the folder
files = folderInfo.GetFiles("*.*");

if (files != null)
{
//Loop through each document and upload it separately
foreach (FileInfo file in files)
{
//Console.WriteLine(file.FullName);
clientContext.Load(folder);
clientContext.ExecuteQuery();
UploadDocument(clientContext, file.FullName, folder.ServerRelativeUrl + "/" + file.Name);
}//foreach (System.IO.FileInfo file in files)

subDirs = folderInfo.GetDirectories();

//Loop through each folder recursively
foreach (DirectoryInfo dirInfo in subDirs)
{
Folder subFolder = folder.Folders.Add(dirInfo.Name);
clientContext.ExecuteQuery();
UploadFolder(clientContext, dirInfo, subFolder);
}//foreach (System.IO.DirectoryInfo dirInfo in subDirs)
}//if (files != null)
}//try
catch(Exception ex)
{
MessageBox.Show(ex.Message, "UploadFolder", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}//public static void UploadFolder(ClientContext clientContext, System.IO.DirectoryInfo folderInfo, Folder folder)
#endregion

#region UploadDocument
///
/// Method to upload document in the folder
///

/////////public static void UploadDocument(ClientContext clientContext, string sourceFilePath, string serverRelativeDestinationPath)
{
try
{
using (var fs = new FileStream(sourceFilePath, FileMode.Open))
{
var file = new FileInfo(sourceFilePath);
//Upload each document to the destination folder
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, serverRelativeDestinationPath, fs, true);
}//using (var fs = new FileStream(sourceFilePath, FileMode.Open))
}//try
catch (Exception ex)
{
MessageBox.Show(ex.Message, "UploadDocument", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}//UploadDocument(ClientContext clientContext, string sourceFilePath, string serverRelativeDestinationPath)
#endregion

}//namespace BrowseAndUploadFiles
}//public partial class Form1 : System.Windows.Forms.Form

 

References:

Thanks for reading 🙂

Keep reading, share your thoughts, experiences. Feel free to contact us to discuss more. If you have any suggestion / feedback / doubt, you are most welcome.

Stay tuned on Knowledge-Junction, will come up with more such articles.

 

2 thoughts on “SharePoint Online – Browse folder from PC and upload to SharePoint Document library

This site uses Akismet to reduce spam. Learn how your comment data is processed.