记录1些经常用SharePoint Client Object访问并管制SharePoint
List或Library的事例。

  首先,全体应用SharePoint Client
Object的.NET工程都急需引用Microsoft.SharePoint.Client.dllMicrosoft.SharePoint.Client.Runtime.dll那四个类库。这里提供一个下载:Microsoft.SharePoint.Client.zip

  下面是一对例子:

壹.
从内定的List或Library中找出Folder

图片 1图片 2GetFolderInList

/// <summary>
/// Get folder in the specific SharePoint List.
/// </summary>
/// <param name=”clientContext”></param>
/// <param name=”listName”></param>
/// <param name=”folderServerRelativeUrl”></param>
/// <returns> If the folder does not exist in the specific SharePoint List return null, else return the folder object.</returns>
public static Folder GetFolderInList(ClientContext clientContext, String listName, String folderServerRelativeUrl)
{
    Folder existingFolder = null;

    Web web = clientContext.Web;
    ListCollection lists = web.Lists;
    existingFolder = web.GetFolderByServerRelativeUrl(folderServerRelativeUrl);
    clientContext.Load(existingFolder);

    try
    {
        clientContext.ExecuteQuery();
    }
    catch 
    {
        existingFolder = null;
    }

    return existingFolder;
}

   listName为所要查询的List或Library的名称,不带路径U凯雷德L。folderServerRelativeUrl为所要查询的Folder的相对路径,如“/sitename/library/folder/subfolder/”。使用的时候供给传入ClientContext对象。若是待查询的Folder存在则赶回对应的Microsoft.SharePoint.Client.Folder对象,否则再次来到null。

 

  1. 从内定的U凯雷德L中规定已存在的Folder

图片 3图片 4FindExistFolder

/// <summary>
/// Find the exist folder in the given URL.
/// </summary>
/// <param name=”clientContext”></param>
/// <param name=”listName”></param>
/// <param name=”folderServerRelativeUrl”></param>
/// <returns>Returns the existed SharePoint Folder object.</returns>
private static Folder FindExistFolder(ClientContext clientContext, string listName, string folderServerRelativeUrl)
{
    Web web = clientContext.Web;
    List list = web.Lists.GetByTitle(listName);

    Folder folder = GetFolderInList(clientContext, listName, folderServerRelativeUrl);

    if (folder == null)
    {
        int iLastSlashPos = folderServerRelativeUrl.LastIndexOf(“/”);
        if (iLastSlashPos > 0)
        {
            // if current folder does not exist, back to the parent folder.
            string parentFolderUrl = folderServerRelativeUrl.Substring(0, iLastSlashPos);
            return FindExistFolder(clientContext, listName, parentFolderUrl);
        }
    }
    return folder;
}

  listName为所要查询的List或Library的名号,不带路径U帕杰罗L。folderServerRelativeUrl为所要查询的Folder的相对路径,如“/sitename/library/folder/subfolder/”。使用的时候要求传入ClientContext对象。该办法通过递归调用的措施从给定的U奇骏L中找出从哪一级伊始的Folder在List或Library中是存在的。例如,给定一个Folder的周旋地址“/sitename/library/folder/subfolder1/subfolder1_1/subfolder1_1_1/”,该方式将从最后二个folder起头开始展览递归,重回存在的丰硕Folder对象。尽管全数的folder均不存在,则赶回null。

 

3.
经过给定的U福特ExplorerL在List或Library中创设Folder

图片 5图片 6EnsureFolderExist

/// <summary>
/// Check if the folder exists in the target list, if it does not, create the folders level by level.
/// </summary>
/// <param name=”clientContext”></param>
/// <param name=”listName”></param>
/// <param name=”folderServerRelativeUrl”></param>
public static void EnsureFolderExist(ClientContext clientContext, string listName, string folderServerRelativeUrl)
{
    // Remove the last character ‘/’ from the string folderServerRelativeUrl.
    if (folderServerRelativeUrl.Length > 0 && folderServerRelativeUrl.Last().Equals(‘/’))
    {
        folderServerRelativeUrl = folderServerRelativeUrl.Substring(0, folderServerRelativeUrl.Length – 1);
    }

    Web web = clientContext.Web;
    List list = web.Lists.GetByTitle(listName);

    Folder folder = FindExistFolder(clientContext, listName, folderServerRelativeUrl);

    if (folder != null)
    {
        // Get the new folders path string part.
        string s = folderServerRelativeUrl.Replace(folder.ServerRelativeUrl, string.Empty);
        if (s.Length > 0 && s.First().Equals(‘/’))
        {
            s = s.Substring(1, s.Length – 1);
        }

        string[] arr = s.Split(‘/’);
        if (arr.Length > 0)
        {
            string tmp = string.Empty;
            // Create new folders level by level.
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i].Trim().Length > 0)
                {
                    tmp += “/” + arr[i];
                    folder.Folders.Add(folder.ServerRelativeUrl + tmp);
                    clientContext.Load(folder);
                    clientContext.ExecuteQuery();
                }
            }
        }
    }
}

  顾名思义,该方式借助于FindExistFolder方法首先从给定的folder相对路径中找出已存在的folder,然后逐级成立folder。

 

四.
选择Microsoft.SharePoint.Client.FileCollection.Add方法向目的Library中开创或改动文件

图片 7图片 8UploadFileToList

/// <summary>
/// Upload a document to the specific SharePoint List.
/// </summary>
/// <param name=”clientContext”></param>
/// <param name=”listName”></param>
/// <param name=”documentUrl”>The target document path, e.g. /site/library/folder/word1.docx.</param>
/// <param name=”documentStream”></param>
/// <param name=”contentType”>ContentType string</param>
public static void UploadFileToList(ClientContext clientContext, string listName, string documentUrl, byte[] documentStream, string contentType)
{
    Web web = clientContext.Web;
    List list = web.Lists.GetByTitle(listName);
    bool bTarFileExist = true;

    // Try to load the target document.
    Microsoft.SharePoint.Client.File targetFile = web.GetFileByServerRelativeUrl(documentUrl);
    targetFile.RefreshLoad();
    clientContext.Load(targetFile);

    try
    {
        clientContext.ExecuteQuery();
    }
    catch 
    {
        bTarFileExist = false;
    }

    // If the target document does exist.
    if (bTarFileExist)
    {
        // If the target document is checked out by another user, execute UndoCheckOut.
        if (targetFile.CheckOutType != CheckOutType.None)
        {
            targetFile.UndoCheckOut();
        }

        // Check out the target document before uploading.
        targetFile.CheckOut();
    }

    // Construct the target document object.
    FileCreationInformation newItemInfo = new FileCreationInformation();
    newItemInfo.Content = documentStream;
    newItemInfo.Overwrite = true;
    newItemInfo.Url = documentUrl;
    Microsoft.SharePoint.Client.File uploadFile = list.RootFolder.Files.Add(newItemInfo);

    // Get target file ContentType.
    ContentType newFileContentType = null;
    if (!defaultContentTypes.Contains(contentType))
    {
        ContentTypeCollection listContentTypes = list.ContentTypes;
        clientContext.Load(listContentTypes, types => types.Include(type => type.Id, type => type.Name, type => type.Parent));
        var result = clientContext.LoadQuery(listContentTypes.Where(c => c.Name == contentType));
        clientContext.ExecuteQuery();
        newFileContentType = result.FirstOrDefault();
    }

    // Set target file ContentType with the correct value.
    clientContext.Load(uploadFile.ListItemAllFields);
    if (newFileContentType != null)
    {
        uploadFile.ListItemAllFields[“ContentTypeId”] = newFileContentType.Id.ToString();
    }
    uploadFile.ListItemAllFields.Update();
    
    // Check in the docuemnt with a draft version.
    uploadFile.CheckIn(string.Empty, CheckinType.MinorCheckIn);
    // Excute the document upload.
    clientContext.ExecuteQuery();
}

  该方法首先依照传入的documentUrl判断文件是不是业已存在,若是存在则须求先将文件check
out或undo check
out,然后通过Microsoft.SharePoint.Client.FileCollection.Add的法子上传文件。假诺指标library中有ContextType的限定,则还须要钦命文件的ContentType,defaultContentTypes是二个存放钦点ContentType的静态String数组,固然传入的contentType字符串不在defaultContentTypes数组中,则要求给文件钦赐新的ContentType。

 

5.
运用Microsoft.SharePoint.Client.File.SaveBinaryDirect方法向目的Library中开创或修改文件

图片 9图片 10UploadFileToListByFileStream

/// <summary>
/// Upload a document to the specific SharePoint List.
/// </summary>
/// <param name=”clientContext”></param>
/// <param name=”listName”></param>
/// <param name=”documentUrl”>The target document path, e.g. /site/library/folder/word1.docx.</param>
/// <param name=”fs”></param>
/// <param name=”contentType”></param>
public static void UploadFileToListByFileStream(ClientContext clientContext, string listName, string documentUrl, FileStream fs, string contentType)
{
    Web web = clientContext.Web;
    List list = web.Lists.GetByTitle(listName);
    bool bTarFileExist = true;

    // Try to load the target document.
    Microsoft.SharePoint.Client.File targetFile = web.GetFileByServerRelativeUrl(documentUrl);
    targetFile.RefreshLoad();
    clientContext.Load(targetFile);

    try
    {
        clientContext.ExecuteQuery();
    }
    catch
    {
        bTarFileExist = false;
    }

    // If the target document does exist.
    if (bTarFileExist)
    {
        // If the target document is checked out by another user, execute UndoCheckOut.
        if (targetFile.CheckOutType != CheckOutType.None)
        {
            targetFile.UndoCheckOut();
        }

        // Check out the target document before uploading.
        targetFile.CheckOut();
        clientContext.ExecuteQuery();
    }

    // Upload file.
    Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, documentUrl, fs, true);
    
    // Get the new file.
    Microsoft.SharePoint.Client.File newFile = web.GetFileByServerRelativeUrl(documentUrl);
    newFile.RefreshLoad();
    clientContext.Load(newFile);
    clientContext.ExecuteQuery();

    // Get target file ContentType.
    ContentType newFileContentType = null;
    if (!defaultContentTypes.Contains(contentType))
    {
        ContentTypeCollection listContentTypes = list.ContentTypes;
        clientContext.Load(listContentTypes, types => types.Include(type => type.Id, type => type.Name, type => type.Parent));
        var result = clientContext.LoadQuery(listContentTypes.Where(c => c.Name == contentType));
        clientContext.ExecuteQuery();
        newFileContentType = result.FirstOrDefault();

        // Set new file ContentType with the correct value.
        clientContext.Load(newFile.ListItemAllFields);
        newFile.ListItemAllFields[“ContentTypeId”] = newFileContentType.Id.ToString();
        newFile.ListItemAllFields.Update();
    }

    // Check in the docuemnt with a draft version.
    newFile.CheckIn(string.Empty, CheckinType.MinorCheckIn);
    // Excute the document upload.
    clientContext.ExecuteQuery();
}

  与UploadFileToList方法类似,该格局通过Microsoft.SharePoint.Client.File.SaveBinaryDirect方法向指标Library中上传文书,接收FileStream而不是文本的字节数组。

 

陆.
读取List或Library中的数据并回到钦命格式的XML文书档案对象

图片 11图片 12GetXmlFromLibrary

public static XDocument GetXmlFromLibrary(string siteUrl, string listName)
{
    string host = (new Uri(siteUrl)).Host;
    XElement root = new XElement(“Items”);

    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
        Web web = clientContext.Web;
        List list = web.Lists.GetByTitle(listName);

        CamlQuery camlQuery = new CamlQuery();
        camlQuery.ViewXml = @”<View>
                                <ViewFields>
                                  <FieldRef Name=’Title’/>
                                  <FieldRef Name=’InsideTrackCategories’/>
                                </ViewFields>
                                <RowLimit>0</RowLimit>
                              </View>”;

        ListItemCollection listItems = list.GetItems(camlQuery);
        clientContext.Load(list);
        //clientContext.Load(listItems);
        clientContext.Load(listItems, s => s.Include(c => c.Id, c => c.DisplayName, c => c.FieldValuesAsText, c => c.FieldValuesForEdit));
        clientContext.ExecuteQuery();                

        foreach (ListItem item in listItems)
        {
            XElement eleTitle = new XElement(“Title”, item.FieldValuesAsText[“Title”].ToString());
            XElement eleUrl = new XElement(“Url”, string.Concat(“http://”, host, item.FieldValuesAsText[“FileRef”].ToString()));
            XElement eleInsideCategories = new XElement(“InsideCategories”);
            string s = item.FieldValuesAsText[“InsideTrackCategories”];
            if (!string.IsNullOrEmpty(s))
            {
                string[] arr = s.Split(‘;’);
                foreach (string tmp in arr)
                {
                    XElement eleCategory = new XElement(“Category”, tmp);
                    eleInsideCategories.Add(eleCategory);
                }
            }

            XElement eleItem = new XElement(“Item”, eleTitle, eleUrl, eleInsideCategories);
            root.Add(eleItem);
        }
    }

    XDocument doc = new XDocument();
    doc.Add(root);
    return doc;
}

  该措施比较简单,通过点名的siteUrl和listName从List或Library中读取钦定字段的多寡,然后依据一定的格式重临XML文书档案对象。下边是所再次来到的XML文书档案对象的协会:

<?xml version=”1.0″ encoding=”utf-8″?>
<Items>
  <Item>
    <Title></Title>
    <Url></Url>
    <InsideCategories>
      <Category></Category>
      <Category></Category>
      <Category></Category>
    </InsideCategories>
  </Item>
  <Item>
    <Title></Title>
    <Url></Url>
    <InsideCategories>
      <Category></Category>
    </InsideCategories>
  </Item>
</Items>

  字段InsideTrackCategories是Lookup类型,并且同意有四个值,当有四个值存在时,SharePoint中用分号进行分隔。

 

  那里记录1些有关SharePoint客户端对象模型应用方面包车型客车篇章,方便未来翻看:

http://msdn.microsoft.com/zh-cn/library/ee857094.aspx

http://msdn.microsoft.com/en-us/library/ee956524.aspx

http://blog.csdn.net/lgm97/article/details/6455361

http://ranaictiu-technicalblog.blogspot.com/2010/03/sharepoint-2010-manage.html

http://www.cnblogs.com/Sunmoonfire/archive/2011/01/18/1937884.html

相关文章

网站地图xml地图