We can use the following code for uploading a document to document library.
// create a filestream object and open an existing file for reading its contents
FileStream oFileStream = File.OpenRead(@”C:\G.doc”);
byte[] content = new byte[oFileStream.Length];
// store the contents in a byte array
oFileStream.Read(content, 0, (int)oFileStream.Length);
oFileStream.Close();
// create an SPSIte object
using (SPSite objSite = new SPSite(“http://d-1246”))
{
// get reference to the web application or web site
using (SPWeb objWeb = objSite.OpenWeb())
{
// get reference to the document library. Proposal – name of the document library
SPFolder mylibrary = objWeb.Folders[“Proposal”];
objWeb.AllowUnsafeUpdates = true;
// add the file to the document library and update it
SPFile myFile = mylibrary.Files.Add(“MyProposal.doc”, content, true);
mylibrary.Update();
// get the reference to the file just uploaded as a SPListItem for setting permissions
SPListItem myListItem = myFile.Item;
// HasUniqueRoleAssignments – returns false if it inherits permission from parent else true
myListItem.HasUniqueRoleAssignments.ToString());
// BreakRoleInheritance – breaking role inheritance so that we can define our own permissions
myListItem.BreakRoleInheritance(false);
// webroledefinitions – Full Right, Design, Contribute and Read
SPRoleDefinitionCollection webroledefinitions = objWeb.RoleDefinitions;
// group – different groups created in that site
SPGroup group = objWeb.SiteGroups[“MyGroup”];
SPRoleAssignment roleassignment = new SPRoleAssignment(group);
roleassignment.RoleDefinitionBindings.Add(webroledefinitions[“Design”]);
myListItem.RoleAssignments.Add(roleassignment);
// same for the user as well
SPUser user = objWeb.SiteUsers[@”domainname\username”];
SPRoleAssignment roleassignment1 = new SPRoleAssignment(user);
roleassignment1.RoleDefinitionBindings.Add(webroledefinitions[“Full Control”]);
myListItem.RoleAssignments.Add(roleassignment1);
}
}
Bye
