代码的魅力

BI, .NET

导航

用C#操作Person or Group列在SharePoint中

Posted on 2009-02-28 15:26  moge  阅读(328)  评论(0编辑  收藏  举报

确定你添加了 Windows SharePoint Services dll 引用. 代码如下...

 

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
namespace UserNameListTester
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                SPSite siteCollection = new SPSite("http://localhost");
                SPWeb mySite = siteCollection.OpenWeb("/");
                SPListItemCollection listItems = mySite.Lists["UserNameListTester"].Items;
                Console.WriteLine("Read in the existing values****************************");
                for (int i = 0; i < listItems.Count; i++)
                {
                    SPListItem item = listItems[i];
                    Console.WriteLine(item["PersonOrGroupColumn"].ToString());
                }
                Console.WriteLine("Writing new values**************************************");
                for (int i = 0; i < listItems.Count; i++)
                {
                    SPListItem listItem = listItems[i];
                    //listItem["Created By"] = mySite.Users["domain\\cornwell"];
                    // get the current logged on user,SPUser 类型
                    string currentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
                    listItem["Created By"] = mySite.Users[currentUser];
                    listItem.Update();
                }
                Console.WriteLine("Read out changed values*******************************");
                for (int i = 0; i < listItems.Count; i++)
                {
                    SPListItem item = listItems[i];
                    Console.WriteLine(item["PersonOrGroupColumn"].ToString());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Shit: " + ex.Message.ToString() + ex.Source.ToString() + ex.ToString());
            }
            finally
            {
                string foo = Console.ReadLine();
            }
        }
    }
}