Simple steps to upload a file programmatically to
SPDocumentLibrary in SharePoint 2010
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite
site = new SPSite(guidSiteID))
{
using (SPWeb web =
site.OpenWeb())
{
SPDocumentLibrary documentLib =
web.Lists.TryGetList(strAFE_Attachments) as SPDocumentLibrary;
Stream fStream =
fupAttachment.PostedFile.InputStream;
byte[] _byteArray = new
byte[fStream.Length];
fStream.Read(_byteArray, 0, (int)fStream.Length);
fStream.Close();
web.AllowUnsafeUpdates = true;
string _fileUrl = documentLib.RootFolder.Url + "/" + Path.GetFileNameWithoutExtension(fupAttachment.PostedFile.FileName)
+ DateTime.Now.ToString("MMddyyyyHHmmss") + Path.GetExtension(fupAttachment.PostedFile.FileName);
bool IsOverwriteFile = false;
SPFile file =
documentLib.RootFolder.Files.Add(_fileUrl, _byteArray, IsOverwriteFile);
SPListItem item = file.Item;
item["Title"] = _strAFE_No;
item.Update();
file.Update();
web.AllowUnsafeUpdates = false;
}
}
});
Adding Folder and SubFolder to document library in
SharePoint 2010
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite
site = new SPSite(guidSiteID))
{
using (SPWeb web =
site.OpenWeb())
{
SPDocumentLibrary documentLib =
web.Lists.TryGetList(strAFE_Attachments) as SPDocumentLibrary;
#region
Folder Creation
web.AllowUnsafeUpdates = true;
SPListItem newFolder = documentLib.Items.Add("", SPFileSystemObjectType.Folder,
"TestRootFolder");
newFolder.Update();
//Creating Subfolder inside folder
string subFolderUrl = web.Url + "/" + newFolder.Url;
SPListItem subFolder =
documentLib.Items.Add(subFolderUrl, SPFileSystemObjectType.Folder,
"TestSubFolder");
subFolder.Update();
web.AllowUnsafeUpdates = false;
#endregion
}
}
});
awesome write..really helped.
ReplyDeletei am try this code in console app, abd add all .dll but some error like RunWithElevatedPrivileges it is method but use as a type
ReplyDeleteHi Akshay,
DeletePlease ensure you added SharePoint namespace reference. Also check with open and close Braces "{ }"
Hope it helps you :)