Sharepoint2013操作文档库内容的相关操作

  1. 添加对Sharepoint相关DLL的引用:
  2. 设置相关的身份验证凭证方法:
    1.   
  3. 调用相关的Sharepoint方法:
    1.   
  4. 文档库操作完整代码:
    1.   public class SharepointBase   {
  5.         /// <summary>

            /// 存放指定ContentType的静态String数组

            /// </summary>

            private static string[] defaultContentTypes = new string[] { "txt", "doc", "docx", "xls" };

     

            #region ① 从指定的List或Library中找出Folder

            /// <summary>

            /// 从指定的List或Library中找出Folder

            /// 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)

            {

                clientContext.Credentials = CreateNetworkCredential();

                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;

            }

            #endregion

     

            #region ② 从指定的URL中确定已存在的Folder

            /// <summary>

            /// 从指定的URL中确定已存在的Folder

            /// 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)

            {

                clientContext.Credentials = CreateNetworkCredential();

                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;

            }

            #endregion

     

            #region ③ 通过给定的URL在List或Library中创建Folder

            /// <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)

            {

                clientContext.Credentials = CreateNetworkCredential();

                // 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();

                            }

                        }

                    }

                }

            }

            #endregion

     

            #region ④ 使用Microsoft.SharePoint.Client.FileCollection.Add方法向目标Library中创建或修改文件

            /// <summary>

            /// 使用Microsoft.SharePoint.Client.FileCollection.Add方法向目标Library中创建或修改文件

            /// 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)

            {

                clientContext.Credentials = CreateNetworkCredential();

                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();

     

                uploadFile.CheckOut();

                // Check in the docuemnt with a draft version.

                uploadFile.CheckIn(string.Empty, CheckinType.MinorCheckIn);

                // Excute the document upload.

                clientContext.ExecuteQuery();

            }

            #endregion

     

            #region ⑤ 使用Microsoft.SharePoint.Client.File.SaveBinaryDirect方法向目标Library中创建或修改文件

            /// <summary>

            /// 使用Microsoft.SharePoint.Client.File.SaveBinaryDirect方法向目标Library中创建或修改文件

            /// 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)

            {

                clientContext.Credentials = CreateNetworkCredential();

                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();

                }

                newFile.CheckOut();

                // Check in the docuemnt with a draft version.

                newFile.CheckIn(string.Empty, CheckinType.MinorCheckIn);

                // Excute the document upload.

                clientContext.ExecuteQuery();

            }

            #endregion

     

            #region ⑥ 读取List或Library中的数据并返回指定格式的XML文档对象

            /// <summary>

            /// 读取List或Library中的数据并返回指定格式的XML文档对象

            /// </summary>

            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))

                {

                    clientContext.Credentials = CreateNetworkCredential();

                    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);

                        //    }

                        //}

     

                        foreach (var tmp in item.FieldValuesAsText.FieldValues)

                        {

                            XElement eleCategory = new XElement(tmp.Key, tmp.Value);

                            eleInsideCategories.Add(eleCategory);

                        }

     

                        XElement eleItem = new XElement("Item", eleTitle, eleUrl, eleInsideCategories);

                        root.Add(eleItem);

                    }

                }

     

                XDocument doc = new XDocument();

                doc.Add(root);

                return doc;

            }

     

            /// <summary>

            /// 生成身份验证凭证

            /// </summary>

            public static System.Net.NetworkCredential CreateNetworkCredential()

            {

                return new System.Net.NetworkCredential("Administrator", "long123!@#", "ideal.com");

            }

            #endregion

        }

posted @ 2013-03-04 15:08  髙髙  阅读(929)  评论(0编辑  收藏  举报