Monthly Archives: March 2015

Utility to upload files from local system to SP Online

All,

i’ve created a utility (windows form application), here is its requirement

“created a utility that will be used to upload files from local drive ‘D:\Files’ etc and upload it in SharePoint document Library also upload its metadata fields by comparing file name being uploaded with the file name with extension saved in excel file”

see following windows form design

utility

Note: excel file contains columns like “File Name, Date Created, Description etc” so when user give path of excel file and upload any file from the local system it first compare its name with file name exists in excel and then get only relevant row for its meta data fields to upload in O365 document library

see excel file below

excel

after clicking on Connect and Upload button by specifying input fields you will see the files uploaded with its metadata fields

lib

that’s it.

here is form.cs file


using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SP = Microsoft.SharePoint.Client;

namespace SimpleWindowsFormsApp
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
txtUploadStatus.Text = string.Empty;

//DataTable dtExcel = GetExcelSheet_DataTable();
}

private void btnUpload_Click(object sender, EventArgs e)
{
try
{
using (SP.ClientContext clientCtx = new SP.ClientContext(new Uri(txtSiteURL.Text)))
{
clientCtx.Credentials = GetSharePointOnlineCredentials();
SP.Web web = clientCtx.Web;

List docLib = web.Lists.GetByTitle(txtLibraryName.Text);
string[] localDirectoryFileColl = Directory.GetFiles(txtFileSystemPath.Text);//Get all files from file system or local drive path i.e D:/Files/
if (localDirectoryFileColl.Length > 0)
{
FileCreationInformation fileCreateInfo = new FileCreationInformation();
string fileName = string.Empty;
for (int i = 0; i < localDirectoryFileColl.Length; i++)
{
fileName = Path.GetFileName(localDirectoryFileColl[i]);
if (!CheckDocumentExists(clientCtx, web, docLib, fileName))
{
UploadDocumentToLibrary(clientCtx, fileCreateInfo, docLib, localDirectoryFileColl[i], fileName);
txtUploadStatus.Text = txtUploadStatus.Text + fileName + " Uploaded successfully" + Environment.NewLine;
}
}
MessageBox.Show("Files and its metadeta upload successfully.");
}
else
{
MessageBox.Show("No files found on local path you specified.");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private SP.SharePointOnlineCredentials GetSharePointOnlineCredentials()
{
SP.SharePointOnlineCredentials onlineCredentials;

//Start: User Credentials to connect with SharePoint Online
string userName = txtUserEmail.Text;
var password = txtPassword.Text;
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
onlineCredentials = new SP.SharePointOnlineCredentials(userName, securePassword);

return onlineCredentials;
}

private bool CheckDocumentExists(SP.ClientContext clientCtx, SP.Web web, List docLib, string fileName)
{
bool flag = false;

ListItemCollection itemColl = docLib.GetItems(new CamlQuery());
clientCtx.Load(itemColl);
clientCtx.ExecuteQuery();

if (itemColl.Count > 0)
{
foreach (var item in itemColl)
{
SP.File file = item.File;
clientCtx.Load(file);
clientCtx.ExecuteQuery();

if (file.Name == fileName)
{
txtUploadStatus.Text = txtUploadStatus.Text + fileName + " Already exists" + Environment.NewLine;
flag = true;
}
}
}

return flag;
}

private void UploadDocumentToLibrary(SP.ClientContext clientCtx, FileCreationInformation fileCreateInfo, List docLib, string filePath, string fileName)
{
fileCreateInfo.Content = System.IO.File.ReadAllBytes(filePath);
fileCreateInfo.Url = fileName;
SP.File myFile = docLib.RootFolder.Files.Add(fileCreateInfo);
clientCtx.Load(myFile);
clientCtx.ExecuteQuery();

SetDocMetaDataFields(clientCtx, myFile);
}

private void SetDocMetaDataFields(SP.ClientContext clientCtx, SP.File myFile)
{
ListItem listItem = myFile.ListItemAllFields;

listItem[MetaDataFields.AssetTitle] = "";
listItem[MetaDataFields.Publication] = "";
listItem[MetaDataFields.CircaDay] = "";
listItem[MetaDataFields.CircaMonth] = "";
listItem[MetaDataFields.LiveDate] = DateTime.Today;
listItem[MetaDataFields.CircaYear] = "";
listItem[MetaDataFields.Status] = "";
listItem[MetaDataFields.ProvidedBy] = "";
listItem[MetaDataFields.Keywords] = "";
listItem[MetaDataFields.Company] = "";

listItem.Update();
clientCtx.ExecuteQuery();
}

private DataTable GetExcelSheet_DataTable()
{
DataTable dt = new DataTable();
string path = "D:/abc.xlsx";
string Extension = Path.GetExtension(Path.GetFileName(path));
string conStr = string.Empty;
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";
break;
case ".xlsx": //Excel 07
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;'";
break;
}
conStr = String.Format(conStr, path);
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
cmdExcel.Connection = connExcel;

connExcel.Open();
string SheetName = "Sheet1";
cmdExcel.CommandText = "SELECT * From [" + SheetName + "$]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();

return dt;
}
}

public class MetaDataFields
{
public const string AssetTitle = "AssetTitle";
public const string Publication = "Publication";
public const string CircaDay = "CircaDay";
public const string CircaMonth = "CircaMonth";
public const string LiveDate = "LiveDate";
public const string CircaYear = "CircaYear";
public const string Status = "Status";
public const string ProvidedBy = "ProvidedBy";
public const string Keywords = "Keywords";
public const string Company = "Company";
}
}