确定你添加了 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();
}
}
}
}