Skip to main content

Download User Profile Pictures from SharePoint 2010 - CSOM

In this post I am trying to explain how we can download UserProfie pictures from SharePoint 2010 on premise environment using CSOM code
  • Two input files:
    • CSV file contains list of users and Email ids(csvInput.csv)
    • Xml input file contains input parameters(InputXml.xml)

CSV File format:
User ID,First Name,Surname,E-mail,
1233,veera,induvasi,veera@abc.com,
1333,mahesh,gupta,mg@abc.com,
2345,abc,azx,abc@abc.com,

InputXml File format:

<Element>
  <InputDetails>
    <siteUrl>http://abc.com</siteUrl>
    <ExportImageLocation>c:\Download</ExportImageLocation>
    <InputCSVFullPath>c:\UserProfile\csvInput.csv</InputCSVFullPath>
    <loginName>create.idea@abc.com</loginName>
    <Password>#####</Password>
  </InputDetails>
</Element>

Xml parameter Details:
<siteUrl> - SharePoint site url
<ExportImageLocation>-Location of the folder where you want to download User Profile pictures
<InputCSVFullPath>- Input CSV file location
<loginName>- Login Name
-password

Just create console app and overwrite the content of “program.cs” file with below code


using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.UserProfiles;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace ExportUserPictureCSOM
{
class Program
{
static void Main(string[] args)
{

XmlDocument doc = new XmlDocument();
doc.Load("InputXml.xml");
string siteUrl = string.Empty;
string password = string.Empty;
string exportImageLocation = string.Empty;
string inputCSVLocation = string.Empty;
string logfileName = string.Empty;
string loginName=string.Empty;         
XmlNodeList root = doc.SelectNodes("Element/InputDetails");
if (root == null)
{
Console.WriteLine("Error Reading Input File");
return;
}

foreach (XmlNode input in root)
{
siteUrl = input["siteUrl"].InnerText;
exportImageLocation = input["ExportImageLocation"].InnerText;
inputCSVLocation = input["InputCSVFullPath"].InnerText;
loginName = input["loginName"].InnerText;

}

if (siteUrl == string.Empty || exportImageLocation == string.Empty || inputCSVLocation == string.Empty || loginName == string.Empty || password == string.Empty)
{
Console.WriteLine("Missing Mandatory Input parameter");
return;
}

         
ClientContext clientContext = new ClientContext(siteUrl);
FormsAuthenticationLoginInfo credentials = new FormsAuthenticationLoginInfo(loginName, password);
//  clientContext.Credentials = credentials;
clientContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
clientContext.FormsAuthenticationLoginInfo = credentials;
Microsoft.SharePoint.Client.Web site = clientContext.Web;
clientContext.Load(site);
clientContext.ExecuteQuery();
Console.WriteLine("Title: {0}", site.Title);
var reader = new StreamReader(System.IO.File.OpenRead(inputCSVLocation));
int count = 0;
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
count++;
if (count > 1) //Start from Second Line
{

string email = getEmailID(line);

string userID = line.Split(',')[0].Replace("\"", "");
string firstName = line.Split(',')[1].Replace("\"", "");
string surName = line.Split(',')[2].Replace("\"", "");
email = "i:0#.f|infocentre|" + email;
try
{
                                    
var user = site.EnsureUser(email);

string pictureUrl = null;
clientContext.Load(user);
clientContext.ExecuteQuery();

string newfileName = firstName + "_" +  surName + "_" + userID + ".jpg";
newfileName = Regex.Replace(newfileName, @"[#/?:,*""><~]+", "", RegexOptions.Compiled);
newfileName = exportImageLocation + @"\" + newfileName;

string fileUrl = getImageUrl(email, clientContext, site);

if (fileUrl != null)
{

    Uri destFileName = new Uri(fileUrl);
    string server = destFileName.AbsoluteUri.Replace(destFileName.AbsolutePath, "");
    string serverrelative = destFileName.AbsolutePath;
    Microsoft.SharePoint.Client.FileInformation f = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, serverrelative);


    using (var fileStream = new FileStream(newfileName, FileMode.Create))
    {
        f.Stream.CopyTo(fileStream);
    }
}
else
{

    Console.WriteLine("User Image not found:" + email);

}
}
catch (Exception ex)
{
Console.WriteLine("Error getting User Details :" + email);
                                  
}
}
}

       

Console.ReadKey(true);
Console.WriteLine();
}

private static string getImageUrl(string userAccount, ClientContext clientContext, Web site)
{
          

var user = site.EnsureUser(userAccount);

string pictureUrl = null;
clientContext.Load(user);
clientContext.ExecuteQuery();


int userId = user.Id;
CamlQuery query = new CamlQuery();

query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='ID' />" +
"<Value Type='Integer'>" + userId + "</Value>" +
"</Eq></Where></Query><ViewFields><FieldRef Name='Picture'/>" +
"</ViewFields></View>";

ListItemCollection items = clientContext.Web.SiteUserInfoList.GetItems(query);

clientContext.Load(items);
clientContext.ExecuteQuery();

foreach (ListItem item in items)
{
FieldUrlValue picture = (FieldUrlValue)item["Picture"];
if (picture != null)
{
//Console.WriteLine(picture.Url);
pictureUrl = picture.Url;
}
}
        

return pictureUrl;
}

private static string getEmailID(string line)
{
string[] userValues = line.Split(',');
string email = string.Empty;

foreach (var item in userValues)
{
if (item.Contains('@'))
{
email = item.Replace("\"", "");
break;
}
}
return email;
}
}
}


More Details about each part of the code as follows:
Add below references assemblies to your project


Based on your SharePoint authentication modify below code. Currently I am using farm based authentication
            ClientContext clientContext = new ClientContext(siteUrl);
            FormsAuthenticationLoginInfo credentials = new FormsAuthenticationLoginInfo(loginName, password);
            //  clientContext.Credentials = credentials;
            clientContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
            clientContext.FormsAuthenticationLoginInfo = credentials;

Run the console app and go to c:\Download you can see list of user profile pictures which are mentioned in input csv file


Comments

Popular posts from this blog

Update Choice Field values through powerShell

Scenario: updating choice column option value for all the columns in a site collection including  sub sites. Solution ; Below script will iterate through all the sites and sub sites of site collection and finds the  choice column " choiceColumnName" and  will change the value "Choice 1" to "Option 1". Powerhsell Script: param($url = $(Read-Host -prompt "Root Site Collection Url")) #Get the PowerShell Snapin if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {     Add-PSSnapin "Microsoft.SharePoint.PowerShell" } #Get Root Site $root = Get-SPSite $url #If site was found / valid if($root -ne $null) {      foreach($subSite in $root.AllWebs)      {                  $subSiteTitle = $subSite.Title                 Write-Host $subSiteTitle -ForegroundColor Magenta                 $subSiteURL = $subSite.Url                 Write-Host $subSiteURL -Foregroun

PowerShell script to count number of list and library items in a site for SharePoint Online and MOSS 2007

This below script mainly helps to get the site item count for both SharePoint Online and MOSS 2007. This will be useful when you are migrating site from MOSS2007 to SharePoint online. Script requires input csv file which contains list of site url as below Input.CSV SiteUrl http://testsite1.com http://tetsite.com when you execute the script, you need to provide 2 input parameters 'Enter input csv path with file name'   - c:\script\input.csv Enter Output Path- c:\script\outpu.csv Script for SharePoint 2007 #clear the PowerShell window cls   $CsvPath = Read-Host -Prompt 'Enter input csv path with file name'   $ReportPath = Read-Host -Prompt 'Enter Output Path' # Exclude the following libaries / lists $excludeLists = @( "Master Page Gallery" ,                 "User Information List" ,                 "TaxonomyHiddenList" ,                 "Theme Gallery" ,