Write a SPFieldUser

If you have a list which contains a SPFieldUser field (with multiple selection), you can add users too it with the following code:

using (SPSite site = new
SPSite(“http://site”))

{

using (SPWeb web = site.AllWebs[“Web”])

<span style="font-family:Consolas;font-size:10pt">    {<br /> </span>

   <span style="font-family:Consolas;font-size:10pt">    <span style="color:#2b91af">SPList</span> list = web.Lists[<span style="color:#a31515">"List"</span>];<br /> </span>

    <span style="font-family:Consolas;font-size:10pt">    <span style="color:#2b91af">SPListItem</span> item = list.Items[0];<br /> </span>

    <span style="font-family:Consolas;font-size:10pt">    <span style="color:#2b91af">SPFieldUserValueCollection</span> values = (<span style="color:#2b91af">SPFieldUserValueCollection</span>)item[<span style="color:#a31515">"Users"</span>];<br /> </span>

    <span style="font-family:Consolas;font-size:10pt">    <span style="color:#2b91af">SPUserCollection</span> users = web.AllUsers;<br /> </span>

    <span style="font-family:Consolas;font-size:10pt">    <span style="color:blue">foreach</span> (<span style="color:#2b91af">SPUser</span> user <span style="color:blue">in</span> users)<br /> </span>

    <span style="font-family:Consolas;font-size:10pt">    {<br /> </span>

        <span style="font-family:Consolas;font-size:10pt">        values.Add(<span style="color:blue">new</span><br /> <span style="color:#2b91af">SPFieldUserValue</span>(web, user.ID, user.Name));<br /> </span>

    <span style="font-family:Consolas;font-size:10pt">    }<br /> </span>

    <span style="font-family:Consolas;font-size:10pt">    item[<span style="color:#a31515">"Users"</span>] = values;<br /> </span>

    <span style="font-family:Consolas;font-size:10pt">    item.Update();<br /> </span>

<span style="font-family:Consolas;font-size:10pt">    }<br /> </span>

}

In this example the list “List” would contain a field with the name “Users”, which takes users. All web users are added to the field “Users” of the first list item, which is then updated.