upload files from sharepoint document to azure blob storage using c#

public static void GetFiles()
{
// Azure Blob Storage Code
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting(“StorageConnectionString”));

CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

CloudBlobContainer container = blobClient.GetContainerReference(“mycontainer”);

container.CreateIfNotExists();

// Sharepoint Object Model Code
ClientContext clientContext = new ClientContext(“http://ipaddess:8080/”);
clientContext.Credentials = new NetworkCredential(“username”, “password”);

Web web = clientContext.Web;
clientContext.Load(web);
clientContext.Load(web.Lists);
clientContext.Load(web, wb => wb.ServerRelativeUrl);
clientContext.ExecuteQuery();

List list = web.Lists.GetByTitle(“Shared Documents”);
clientContext.Load(list);
clientContext.ExecuteQuery();

Folder folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + @”Shared Documents\2″);
clientContext.Load(folder);
clientContext.ExecuteQuery();

CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = @”<View Scope=’Recursive’>
<Query>
</Query>
</View>”;
camlQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
FileInformation fileInfo;
CloudBlockBlob blockBlob;

foreach (var item in listItems)
{
clientContext.Load(item.File);
clientContext.ExecuteQuery();

fileInfo = File.OpenBinaryDirect(clientContext, (string)item.File.ServerRelativeUrl);
blockBlob = container.GetBlockBlobReference(item.File.Name);

using (var fileStream = fileInfo.Stream)
{
blockBlob.UploadFromStream(fileStream);
}
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s