sharepoint 2012 服务端对象模型的一些操作方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using Microsoft.SharePoint;
using System.IO;
using KMS.Common.Enums;
using KMS.Common.Log;
using System.Configuration;
using System.Web;

namespace KMSMossServices
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“KMSMossServices”。
    public class KMSMossServices : IKMSMossServices
    {
        private SPUserToken userToken = null;
        public void DoWork()
        {
        }

        #region 唤醒MOSS服务  WarmUpMoss()
        /// <summary>
        /// 唤醒MOSS服务  WarmUpMoss()
        /// </summary>
        /// <returns></returns>
        public string WarmUpMoss()
        {
            //return ViewerUtil.WarmUpMoss();
            KLog.Info("Start Warmup moss....", Modules.MossService);
            string siteurl = ConfigurationManager.AppSettings["MossSiteUrl"];
            if (siteurl != null && siteurl.Length > 0)
            {
                using (SPSite site = new SPSite(siteurl, GetUserToken(siteurl, ConfigurationManager.AppSettings["MossSiteUser"])))
                {

                }
                KLog.Info("Finish Warmup moss....", Modules.MossService);
                return "OK";
            }
            else
            {
                KLog.Info("Fail to  Warmup moss, MossSiteUrl missing...", Modules.MossService);
                return "Fail";
            }

        }
        #endregion

        #region 创建文件夹
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="url">待创建文件夹url</param>
        /// <param name="web">web网站</param>
        public void CreateFolder(string url, string sitUrl, string userName)
        {
            try
            {
                using (SPSite site = new SPSite(sitUrl, GetUserToken(sitUrl)))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        string strUrl = url.TrimEnd('/');
                        SPFolder folder = web.GetFolder(strUrl);
                        while (!folder.Exists)
                        {
                            if (web.Url.Equals(strUrl, StringComparison.OrdinalIgnoreCase))
                                break;
                            strUrl = strUrl.Substring(0, strUrl.LastIndexOf('/')).TrimEnd('/');
                            folder = web.GetFolder(strUrl);
                        }
                        string relativeFolderPath = url.Replace(strUrl, "").Trim('/');
                        var folderNameAry = relativeFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                        var list = web.GetList(strUrl);
                        var parentUrl = strUrl;
                        foreach (var folderName in folderNameAry)
                        {
                            var itemUrl = string.Format("{0}/{1}", parentUrl, folderName);
                            folder = web.GetFolder(itemUrl);
                            if (!folder.Exists)
                            {
                                SPFolder newFolder = folder.ParentFolder.SubFolders.Add(string.Format("{0}/{1}", folder.ParentFolder.ServerRelativeUrl.TrimEnd('/'), folderName));
                                //change the status to approved
                                if (newFolder.Item.ModerationInformation.Status == SPModerationStatusType.Pending)
                                {
                                    newFolder.Item.ModerationInformation.Status = SPModerationStatusType.Approved;
                                    newFolder.Item.Update();
                                }
                            }
                            parentUrl = itemUrl;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 创建 文件夹1
        /// <summary>
        /// 创建 文件夹1
        /// </summary>
        /// <param name="siteUrl">站点url</param>
        /// <param name="parentFolderURL">父文件夹url</param>
        /// <param name="folderName">待创建文件夹名称</param>
        /// <returns></returns>
        public string CreateFolder1(string siteUrl, string parentFolderURL, string folderName, string userName)
        {
            try
            {
                if (string.IsNullOrEmpty(parentFolderURL) || string.IsNullOrEmpty(folderName))
                    throw new Exception("输入的父文件夹url或新文件夹名称是空字符串!");
                using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl)))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPFolder folder = web.GetFolder(parentFolderURL);
                        SPFolder newFolder = folder.SubFolders.Add(folderName);
                        if (newFolder.Item.ModerationInformation.Status == SPModerationStatusType.Pending)
                        {
                            newFolder.Item.ModerationInformation.Status = SPModerationStatusType.Approved;
                            newFolder.Item.Update();
                        }
                        return newFolder.Url;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 删除文件夹
        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="siteUrl">站点url</param>
        /// <param name="folderUrl">待删除文件夹url</param>
        public void DeleteFolder(string siteUrl, string folderUrl, string userName)
        {
            try
            {
                if (string.IsNullOrEmpty(siteUrl) || folderUrl == null)
                    throw new Exception("输入参数存在空值!");
                using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl)))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPFolder folder = web.GetFolder(folderUrl);
                        folder.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 修改MOSS文件夹
        /// <summary>
        /// 修改MOSS文件夹
        /// </summary>
        /// <param name="siteUrl">站点url</param>
        /// <param name="oldFolderUrl">原文件夹url</param>
        /// <param name="newFolderName">新文件夹名称</param>
        public void UpdateFolder(string siteUrl, string oldFolderUrl, string newFolderName, string userName)
        {
            try
            {
                if (string.IsNullOrEmpty(siteUrl) || string.IsNullOrEmpty(oldFolderUrl) || string.IsNullOrEmpty(newFolderName))
                    throw new Exception("输入参数存在空值!");
                using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl)))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPListItem item = web.GetListItem(oldFolderUrl);
                        if (item.File != null)
                        {
                            item.File.CheckOut();
                            item["FileLeafRef"] = newFolderName;
                            item.Update();
                            item.File.CheckIn("change name");
                        }
                        else
                        {
                            item["FileLeafRef"] = newFolderName;
                            item.Update();
                        }
                        if (item.ModerationInformation.Status == SPModerationStatusType.Pending)
                        {
                            item.ModerationInformation.Status = SPModerationStatusType.Approved;
                            item.Update();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 上传文件
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="siteUrl">站点url</param>
        /// <param name="fileUrl">文件存放的文件夹地址(包含文件名)</param>
        /// <param name="file">上传文件字节流</param>
        /// <param name="userName">用户名</param>
        public void UpLoadFile(string siteUrl, string fileUrl, byte[] file, string userName, string checkInComment = "")
        {
            try
            {
                using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl, userName)))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        var spFile = web.GetFile(fileUrl);
                        if (spFile.Exists)
                        {
                            SPFileCollection files = web.Files;

                            //files.Add(fileUrl, file, true);
                            files.Add(fileUrl, file, true, checkInComment, false);
                            //spFile.CheckIn("");
                            //spFile.Update();
                        }
                        else
                        {
                            SPFileCollection files = web.Files;
                            files.Add(fileUrl, file);
                        }
                        web.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 读取MOSS文档
        /// <summary>
        /// 读取MOSS文档
        /// </summary>
        /// <param name="siteUrl">站点URL</param>
        /// <param name="fileUrl">文件绝对路径</param>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        public byte[] ReadFile(string siteUrl, string fileUrl, string userName)
        {
            try
            {
                byte[] stream = null;
                using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl, userName)))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        var file = web.GetFile(fileUrl);
                        stream = file.OpenBinary();
                    }
                }
                return stream;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取版本信息
        /// <summary>
        /// 获取版本信息
        /// </summary>
        /// <param name="siteUrl">站点url</param>
        /// <param name="fileUrl">文件路径</param>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        public string GetDocversions(string siteUrl, string fileUrl, string userName)
        {
            try
            {
                StringBuilder result = new StringBuilder();
                using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl, userName)))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPFile file = web.GetFile(fileUrl);
                        SPFileVersionCollection versions = file.Versions;
                        foreach (SPFileVersion version in versions)
                        {
                            //版本号/版本对应url/版本对应创建时间/版本创建人
                            result.AppendFormat("{0}^", version.VersionLabel);
                            result.AppendFormat("{0}^", version.Url);
                            result.AppendFormat("{0}^", version.Created);
                            try
                            {
                                if (version.CreatedBy.ToString().Equals(@"SHAREPOINT\system"))
                                    result.AppendFormat("{0}^", "系统账户");
                                else
                                    result.AppendFormat("{0}^", version.CreatedBy);
                            }
                            catch
                            {
                                result.AppendFormat("{0}^", "系统账户");
                            }
                            result.AppendFormat("{0}$", version.CheckInComment);
                        }
                    }
                }
                return result.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取文档大小
        /// <summary>
        /// 获取文档大小
        /// </summary>
        /// <param name="siteUrl">站点url</param>
        /// <param name="fileUrl">文件路径</param>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        public long GetDocSize(string siteUrl, string fileUrl, string userName)
        {
            try
            {
                long result = 0;
                using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl, userName)))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPFile file = web.GetFile(fileUrl);
                        if (file.Exists)
                        {
                            result = (long)file.TotalLength;
                        }
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 文档审批
        /// <summary>
        /// 文档审批
        /// </summary>
        /// <param name="siteUrl">站点url</param>
        /// <param name="fileUrl">文件路径</param>
        /// <param name="userName">用户名</param>
        /// <param name="bPass">是否通过审批</param>
        /// <param name="comment">审批意见</param>
        /// <returns></returns>
        public void ApproveDoc(string siteUrl, string fileUrl, string userName, bool bPass, string comment)
        {
            using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl, userName)))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPFile file = web.GetFile(fileUrl);
                    if (file.Item.ModerationInformation.Status == SPModerationStatusType.Approved)
                        return;
                    if (bPass)
                        file.Approve(comment);
                    else
                        file.Deny(comment);
                }
            }
        }
        #endregion

        #region 文件夹审批
        /// <summary>
        /// 文件夹审批
        /// </summary>
        /// <param name="siteUrl">站点url</param>
        /// <param name="folderUrl">文件夹路径</param>
        /// <param name="userName">用户名</param>
        /// <param name="bPass">是否通过审批</param>
        /// <param name="comment">审批意见</param>
        /// <returns></returns>
        public void ApproveFolder(string siteUrl, string folderUrl, string userName, bool bPass, string comment)
        {
            using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl, userName)))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPListItem li = web.GetListItem(folderUrl);
                    switch (li.ModerationInformation.Status)
                    {
                        case SPModerationStatusType.Approved:
                            break;
                        case SPModerationStatusType.Pending:
                            {
                                if (bPass)
                                {
                                    li.ModerationInformation.Status = SPModerationStatusType.Approved;
                                    li.Update();
                                }
                                else
                                {
                                    li.ModerationInformation.Status = SPModerationStatusType.Denied;
                                    li.Update();
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        #endregion

        #region 获取文件夹审批信息
        /// <summary>
        /// 获取文件夹审批信息
        /// </summary>
        /// <param name="siteUrl">站点url</param>
        /// <param name="folderUrl">文件夹路径</param>
        /// <returns></returns>
        public List<string> GetApproversOfFolder(string siteUrl, string folderUrl)
        {
            List<string> approvers = new List<string>();
            string userPrefix = ConfigurationManager.AppSettings["MossSiteUserPrefix"];
            using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl)))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    //SPList list = web.GetList(folderUrl);
                    SPFolder folder = web.GetFolder(folderUrl);
                    SPRoleAssignmentCollection oRoleAssignments = folder.Item.RoleAssignments;

                    //SPRoleDefinitionBindingCollection oRoleDefinition = folder.Item.AllRolesForCurrentUser;

                    foreach (SPRoleAssignment oRoleAssignment in oRoleAssignments)
                    {
                        SPPrincipal oPrincipal = oRoleAssignment.Member;

                        try
                        {
                            // Retrieve user groups having permissions on the list
                            if (oPrincipal is SPUser)
                            {
                                SPUser user = (SPUser)oPrincipal;
                                if (oPrincipal.LoginName.StartsWith(userPrefix))
                                {
                                    SPRoleDefinitionBindingCollection rbc = oRoleAssignment.RoleDefinitionBindings;
                                    foreach (SPRoleDefinition rd in rbc)
                                    {
                                        if ((rd.BasePermissions & SPBasePermissions.ApproveItems) == SPBasePermissions.ApproveItems)
                                        {
                                            approvers.Add(oPrincipal.LoginName);
                                            break;
                                        }
                                    }
                                }
                            }
                            /*
                        else
                        {//group
                            SPGroup oRoleGroup = (SPGroup)oPrincipal;
                            if ((oRoleGroup.Name == "Approvers" || oRoleGroup.Name == "审批者") && oRoleGroup.Users.Count > 0)
                            {
                                //string strGroupName = oRoleGroup.Name;
                                // Add code here to retrieve Users inside this User-Group
                                foreach (SPUser approver in oRoleGroup.Users)
                                {
                                    approvers.Add(approver.LoginName);
                                }
                            }
                        }*/

                        }
                        catch (Exception ex)
                        {
                            string msg = ex.Message;
                        }

                    }
                    //default approver
                    if (approvers.Count == 0)
                    {
                        approvers.Add(ConfigurationManager.AppSettings["MossSiteUser"]);
                    }
                }
            }
            return approvers;
        }
        #endregion

        #region 获取文件夹 权限用户组信息
        /// <summary>
        /// 获取文件夹 权限用户组信息
        /// </summary>
        /// <param name="siteUrl">站点url</param>
        /// <param name="folderUrl">文件夹路径</param>
        /// <returns></returns>
        public List<string> GetUserGroupByFolder(string siteUrl, string folderUrl)
        {
            List<string> userGroup = new List<string>();
            string userPrefix = ConfigurationManager.AppSettings["MossSiteUserPrefix"];
            using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl)))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPFolder folder = web.GetFolder(folderUrl);
                    SPRoleAssignmentCollection oRoleAssignments = folder.Item.RoleAssignments;
                    foreach (SPRoleAssignment oRoleAssignment in oRoleAssignments)
                    {
                        SPPrincipal oPrincipal = oRoleAssignment.Member;

                        try
                        {
                            // 检索权限列表中是否包含该用户组
                            //if (oPrincipal is SPUser)
                            //{
                            //    SPUser user = (SPUser)oPrincipal;
                            if (!oPrincipal.LoginName.StartsWith(userPrefix))
                            {
                                userGroup.Add(oPrincipal.LoginName);
                                //SPRoleDefinitionBindingCollection rbc = oRoleAssignment.RoleDefinitionBindings;
                                //foreach (SPRoleDefinition rd in rbc)
                                //{
                                //    if ((rd.BasePermissions & SPBasePermissions.ApproveItems) == SPBasePermissions.ApproveItems)
                                //    {
                                //        userGroup.Add(oPrincipal.LoginName);
                                //        break;
                                //    }
                                //}
                            }
                            //}
                        }
                        catch (Exception ex)
                        {
                            string msg = ex.Message;
                        }
                    }
                }
            }
            return userGroup;
        }
        #endregion

        #region 判断当前用户对当前文件是否有访问权限
        /// <summary>
        /// 判断当前用户对当前文件是否有访问权限
        /// </summary>
        /// <param name="siteUrl">站点url</param>
        /// <param name="fileUrl">文件url</param>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        public string CanAccess(string siteUrl, string fileUrl, string userName)
        {
            string result = string.Empty;
            using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl, userName)))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPFile file = web.GetFile(fileUrl);
                    if (file.Exists)
                    {
                        if (file.CanOpenFile(true))
                        {
                            result = "true|ok";
                        }
                        else
                        {
                            result = "false|无权访问";
                        }
                    }
                    else
                    {
                        result = "false|文件不存在";
                    }
                }
            }
            return result;
        }
        #endregion

        #region 设置moss中的搜索字段
        /// <summary>
        /// 设置moss中的搜索字段
        /// </summary>
        /// <param name="siteUrl">站点url</param>
        /// <param name="fileUrl">文件路径</param>
        /// <param name="kbaseid">kbaseid</param>
        /// <param name="busicat1">1级专业分类</param>
        /// <param name="dutycat1">1级岗位分类</param>
        /// <param name="deptcat1">1级部门分类</param>
        /// <param name="processcat1">1级流程分类</param>
        /// <param name="keywords">关键字</param>
        /// <param name="status">状态,1:上架; 2:下架</param>
        /// <returns></returns>
        public bool SetSearchFeature(string siteUrl, string fileUrl, string kbaseid, string busicat1, string dutycat1, string deptcat1,
                                        string processcat1, string keywords, string status)
        {
            try
            {
                if (string.IsNullOrEmpty(siteUrl) || string.IsNullOrEmpty(fileUrl))
                    throw new Exception("输入参数存在空值!");
                using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl)))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPListItem item = web.GetListItem(fileUrl);
                        if (item.File != null)
                        {
                            //item.ModerationInformation.
                            item.File.CheckOut();
                            if (kbaseid != null)
                                item["kbaseid"] = kbaseid;
                            if (busicat1 != null)
                                item["busicat1"] = busicat1;
                            if (dutycat1 != null)
                                item["dutycat1"] = dutycat1;
                            if (deptcat1 != null)
                                item["deptcat1"] = deptcat1;
                            if (processcat1 != null)
                                item["processcat1"] = processcat1;
                            if (keywords != null)
                                item["kmkeywords"] = keywords;
                            if (status != null)
                                item["kmstatus"] = status;
                            item.Update();
                            item.File.CheckIn("审批通过,加入搜索。");
                        }
                        //if (item.ModerationInformation.Status == SPModerationStatusType.Pending)
                        //    item.File.Approve("");
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }


            return true;
        }
        #endregion

        #region MOSS中移动文件
        /// <summary>
        /// MOSS中移动文件
        /// </summary>
        /// <param name="siteUrl">站点URL</param>
        /// <param name="oldFileUrl">原始文件URL</param>
        /// <param name="newFileUrl">新文件URL</param>
        /// <param name="userName">操作用户</param>
        public void MoveFileInSharePoint(string siteUrl, string oldFileUrl, string newFileUrl, string userName)
        {
            try
            {
                if (string.IsNullOrEmpty(siteUrl) || string.IsNullOrEmpty(oldFileUrl) || string.IsNullOrEmpty(newFileUrl) || string.IsNullOrEmpty(userName))
                    throw new Exception("输入参数有误!");
                using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl, userName)))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPFile file = web.GetFile(oldFileUrl);
                        file.MoveTo(newFileUrl);
                        //if (file.Item.ModerationInformation.Status == SPModerationStatusType.Pending)
                        //    file.Approve("移动文件成功。");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion

        #region 修改MOSS文件名
        /// <summary>
        /// 修改MOSS文件名
        /// </summary>
        /// <param name="siteUrl">站点url</param>
        /// <param name="oldFolderUrl">原文件url</param>
        /// <param name="newFolderName">新文件名称</param>
        public void UpdateFileName(string siteUrl, string oldFileUrl, string newFileName)
        {
            try
            {
                if (string.IsNullOrEmpty(siteUrl) || string.IsNullOrEmpty(oldFileUrl) || string.IsNullOrEmpty(newFileName))
                    throw new Exception("输入参数存在空值!");
                using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl)))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPListItem item = web.GetListItem(oldFileUrl);
                        if (item.File != null)
                        {
                            //item.File.CheckOut();
                            item["FileLeafRef"] = newFileName;
                            item.Update();
                            //item.File.CheckIn("修改文件名");
                            if (item.ModerationInformation.Status == SPModerationStatusType.Pending)
                            {
                                item.File.Approve("审批修改文件名");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion

        #region  MOSS移动文件夹
        /// <summary>
        /// MOSS移动文件夹
        /// </summary>
        /// <param name="siteUrl">站点URL</param>
        /// <param name="oldFolderUrl">原文件夹URL</param>
        /// <param name="newFolderUrl">新文件夹URL</param>
        public void MoveFolderInSharePoint(string siteUrl, string oldFolderUrl, string newFolderUrl)
        {
            if (string.IsNullOrEmpty(siteUrl) || string.IsNullOrEmpty(oldFolderUrl) || string.IsNullOrEmpty(newFolderUrl))
                throw new Exception("输入参数有误!");
            using (SPSite site = new SPSite(siteUrl, GetUserToken(siteUrl)))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPFolder folder = web.GetFolder(oldFolderUrl);
                    folder.MoveTo(newFolderUrl);
                    //if (folder.Item.ModerationInformation.Status == SPModerationStatusType.Pending)
                    //{
                    //    folder.Item.ModerationInformation.Status = SPModerationStatusType.Approved;
                    //    folder.Item.Update();
                    //}
                }
            }
        }
        #endregion

        #region 获取用户凭据
        /// <summary>
        /// 获取用户凭据
        /// </summary>
        /// <param name="SiteUrl">站点URL</param>
        /// <returns></returns>
        private SPUserToken GetUserToken(string SiteUrl)
        {
            if (userToken != null) return userToken;
            //string username = ServiceSecurityContext.Current.WindowsIdentity.Name;
            //string username = @"SPSDemo.com\demoadmin"; ;
            using (SPSite site = new SPSite(SiteUrl))
            {
                /*
                SPWeb web = site.OpenWeb();
                SPUser user = web.AllUsers[username];
                if (user == null) throw new System.UnauthorizedAccessException(string.Format("用户账号:{0}不存在", username));
                userToken = user.UserToken;
                 */
                userToken = site.SystemAccount.UserToken;
                return userToken;
            }
        }
        #endregion

        #region 获取用户凭据
        /// <summary>
        /// 获取用户凭据
        /// </summary>
        /// <param name="url">MOSS站点url</param>
        /// <param name="owner">域\用户名</param>
        /// <returns>凭据</returns>
        private static SPUserToken GetUserToken(string url, string owner)
        {
            SPUserToken ownerToken = null;
            using (var spSite = new SPSite(url))
            {
                using (var spWeb = spSite.OpenWeb())
                {
                    try
                    {
                        //add by zdl,have to config the web.config's fba
                        SPUser user = spWeb.EnsureUser(owner);
                        if (!string.IsNullOrEmpty(owner))
                            ownerToken = spWeb.GetUserToken(owner);
                        else
                            ownerToken = spWeb.CurrentUser.UserToken;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                }
            }
            return ownerToken;
        }
        #endregion


    }

}

posted @ 2012-10-10 14:16  永不言败,自信相伴  阅读(254)  评论(0)    收藏  举报