Archive

Posts Tagged ‘Client Object Model’

Client Object Model – Multi Uploading to Document Libraries

October 12, 2010 1 comment

We have got so many posts that were explaining how to upload a document into SharePoint using the client object Model.

But this is an effort from my end to do the same, but in a different way.

Scenario:

I am trying to upload all the contents of a folder, be files or folders to a document library. This worked out to be quite a bit of code, but I finally achieved it 🙂

I started of with creation of a WPF application. When we run the application, it uploads the documents and folders to the selected document Library.

This is not complete yet, but will definitely useful for many to get started with some serious coding using Client Object Model.

Here are some of the screenshots

Select the folder to be uploaded to SharPoint Document Library.

 

Enter the Share Point Site to which to connect to. Enter the site URL and click connect.

It will display only the Document Libraries, as the scenario assumes that we are currently uploading stuff only to Document Libraries.

Code:

Lets first define the namespace.
namespace SharePointMultiFileUploader
{
}

By default the WPF application creates a class called Main Window, Lets keep it.

public partial class MainWindow : Window

I am defining a public property with return value of  a IDictionary. Here I am storing two sting values.  The document library Title and the document library URL.
public IDictionary<string, string> Lists
{

get
{
return dictDocumentLibraries;
}

}

The first thing that we need is the path on the local system, which is to be uploaded to SharePoint Document Library. I am using the FolderBrowseDialog which is available in windows. I am setting the root folder as Desktop. We can set it to any path from the available list of enum values.

private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
MWF.FolderBrowserDialog folderbrowsedialog = new MWF.FolderBrowserDialog();
folderbrowsedialog.RootFolder = Environment.SpecialFolder.Desktop;
MWF.DialogResult result = folderbrowsedialog.ShowDialog();
if (result == MWF.DialogResult.OK)
{
txtFolderPath.Text = folderbrowsedialog.SelectedPath;
}

}

private void btnConnect_Click(object sender, RoutedEventArgs e)
{
oContext = new SPC.ClientContext(txtSiteURL.Text);
oWeb = oContext.Web;
oContext.Load(oWeb);
oContext.ExecuteQuery();
dictDocumentLibraries = new Dictionary<string, string>(); ;
oDocumentLibraryCollection = oWeb.Lists;
oContext.Load(oDocumentLibraryCollection);
oContext.ExecuteQuery();
foreach(SPC.List List in oDocumentLibraryCollection)
{
if(List.BaseType.Equals(SPC.BaseType.DocumentLibrary))
{
dictDocumentLibraries.Add(List.Title, oWeb.Context.Url +List.Title+”/”);
}
}
cbDocumentLibraryName.ItemsSource = Lists;
cbDocumentLibraryName.DisplayMemberPath=”Key”;
cbDocumentLibraryName.SelectedValuePath=”Value”;
cbDocumentLibraryName.Visibility = Visibility.Visible;
lblDocumentLibraryName.Visibility = Visibility.Visible;
}

private void btnUpload_Click(object sender, RoutedEventArgs e)
{
string[] strrootFolderName = txtFolderPath.Text.Split(‘\\’);
strRootFolder = strrootFolderName[strrootFolderName.Length – 1];
strCurrentURL = cbDocumentLibraryName.SelectedValue.ToString();
UploadFolder(txtFolderPath.Text, strCurrentURL);
}
/// <summary>
///
/// </summary>
/// <param name=”strFolderPath”></param>
private void UploadFolder(string strFolderPath, string strDocumentLibraryPath)
{
try
{
DirectoryInfo dirSelectedFolder = new DirectoryInfo(strFolderPath);
foreach (FileInfo File in dirSelectedFolder.GetFiles())
{
string strCurrentFilePath = File.FullName;
UploadFile(File.Name, strCurrentFilePath, strDocumentLibraryPath,strCurrentPath);
}
foreach (DirectoryInfo subDirectory in dirSelectedFolder.GetDirectories())
{
strCurrentPath = subDirectory.FullName.Substring(txtFolderPath.Text.Length+1);
int iDepth = GetDepth(strCurrentPath,’\\’);
strDocumentLibraryPath =strCurrentURL+strCurrentPath.Replace(‘\\’,’/’);
bool flag=CreateFolder(strDocumentLibraryPath, subDirectory.Name, strCurrentPath,iDepth);
UploadFolder(subDirectory.FullName, strDocumentLibraryPath);
}
}
catch (Exception Ex)
{

}

}
/// <summary>
///
/// </summary>
/// <param name=”strCurrentPath”></param>
/// <param name=”splitter”></param>
/// <returns></returns>
private int GetDepth(string strCurrentPath, char splitter)
{
return strCurrentPath.Split(splitter).Length – 1;
}
/// <summary>
///
/// </summary>
/// <param name=”strPath”></param>
private bool CreateFolder(string strPath, string strFolderName,string strCurrentPath,int iDepth)
{
try
{
if (oList == null)
{
strLibrary = ((System.Collections.Generic.KeyValuePair<string, string>)(cbDocumentLibraryName.SelectedItem)).Key;
oList = oWeb.Lists.GetByTitle(strLibrary);
oContext.Load(oList);
oContext.ExecuteQuery();
}
//Getting the Root Folder
RootFolder = oList.RootFolder;
oContext.Load(RootFolder);
if (iDepth == 0)
{
RootFolder.Folders.Add(strPath);
RootFolder.Update();
oContext.Load(RootFolder);
oContext.ExecuteQuery();
}
string[] strCurrentFolderName = strCurrentPath.Split(‘\\’);
//Getting the Root Folder Collection
currentFolderCollection = oList.RootFolder.Folders;
oContext.Load(currentFolderCollection);
oContext.ExecuteQuery();
for (int iDepthCount = 0; iDepthCount <= iDepth; iDepthCount++)
{
int iFolderIndex = 0;
bool bFolderExists = false;

foreach (SPC.Folder currentFolder in currentFolderCollection)
{
if (currentFolder.Name == strCurrentFolderName[iDepthCount])//string.Format(“/{0}/{1}”, oList.Title, strCurrentPath.Replace(‘\\’, ‘/’)))
{
bFolderExists = true; //The folder exists
CurrentFolder = currentFolderCollection[iFolderIndex];
oContext.Load(CurrentFolder);
oContext.ExecuteQuery();
currentFolderCollection = MovetoNextLevel(currentFolderCollection, iFolderIndex);//Open the folder
oContext.Load(currentFolderCollection);//Load the folder to the context, to make use of it
oContext.ExecuteQuery();
break;
}
else
{
iFolderIndex++;
continue;
}
}
if (bFolderExists == false)//Folder dosen’t exist
{
if (iFolderIndex != 0)
{
currentFolderCollection[iFolderIndex – 1].Folders.Add(strPath);
CurrentFolder = currentFolderCollection[iFolderIndex – 1];
}
else
{
CurrentFolder.Folders.Add(strPath);
currentFolderCollection = CurrentFolder.Folders;
oContext.Load(currentFolderCollection);

CurrentFolder = currentFolderCollection[iFolderIndex];
}
CurrentFolder.Update();
oContext.Load(CurrentFolder);
oContext.Load(currentFolderCollection);
oContext.ExecuteQuery();
currentFolderCollection = CurrentFolder.Folders;
oContext.Load(currentFolderCollection);
oContext.ExecuteQuery();
}
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Data);
}
return false;
}
/// <summary>
///
/// </summary>
/// <param name=”strCurrentFilePath”></param>
private void UploadFile(string strFileName, string strCurrentFilePath, string strDocumentLibraryPath, string strCurrentPath)
{
int iMoveDepth = 0;
String[] strFolder;
if (oList == null)
{
string title = ((System.Collections.Generic.KeyValuePair<string, string>)(cbDocumentLibraryName.SelectedItem)).Key;
oList = oWeb.Lists.GetByTitle(title);
oContext.Load(oList);
CurrentFolder = oList.RootFolder;
oContext.ExecuteQuery();
}
//Split the current directory path.
strFolder = strCurrentPath.Split(‘\\’);
//Get the folder depth
int iDepth = strFolder.Length;
UploadFiles(strCurrentFilePath, strFileName, CurrentFolder);
}

private void UploadFiles(string strCurrentFilePath, string strFileName, SPC.Folder currentFolder)
{
SPC.FileCreationInformation newFile = new SPC.FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(@strCurrentFilePath);
newFile.Url = strFileName;
SPC.File uploadFile = currentFolder.Files.Add(newFile);
oContext.Load(uploadFile);
oContext.ExecuteQuery();
}

/// <summary>
///
/// </summary>
/// <param name=”currentFolderCollection”></param>
/// <param name=”iFolderIndex”></param>
/// <returns></returns>
private SPC.FolderCollection MovetoNextLevel(SPC.FolderCollection currentFolderCollection, int iFolderIndex)
{
return currentFolderCollection[iFolderIndex].Folders;
}
/// <summary>
///
/// </summary>
/// <param name=”sender”></param>
/// <param name=”e”></param>

}
}