By default SharePoint server doesn't allow anonymous users to upload items to document library.
If you try to set permissions on document library for anonymous users like you used to do on custom lists you will see that add, edit and delete items options are grayed out.
This can be issue for public facing WCM sites where you want to allow anonymous useres to post or attach some documents, and you want to store those attachments in your document library.
Best way to solve this is by calling SPSecurity.RunWithElevatedPrivileges.
What this method does is changing context from anonymous to the context in which app pool runs, giving you full permissions.
If you try to execute code from context of anonymous user without calling this method you will get Security exception and user will be redirected and prompted for user name and password
Here is the example:
26 SPSite siteCurrent = SPContext.Current.Site;
27 SPWeb webCurrent = SPContext.Current.Web;
28
29 SPSecurity.RunWithElevatedPrivileges(delegate()
30 {
31 using (SPSite elevatedSite = new SPSite(siteCurrent.ID))
32 {
33 using (SPWeb elevatedWeb = elevatedSite.OpenWeb(webCurrent.ID))
34 {
35 elevatedWeb.AllowUnsafeUpdates = true;
36 SPList SPCandidateList =
elevatedWeb.Lists[Settings.CandidatesListName];
37 SPCandidateList.AnonymousPermMask64 =
SPBasePermissions.ViewListItems |
38 SPBasePermissions.OpenItems |
39 SPBasePermissions.Open |
40 SPBasePermissions.ViewFormPages |
41 SPBasePermissions.AddListItems;
43 // Code for adding items to your list
It's important that you create instance of your "elevated" SPWeb and SPSite inside SPSecurity.RunWithElevatedPrivilages method call.
After uploading item to document library you will notice that value of "Modifed by" column is "System Account"
showing in which context item was added.