Simple steps to upload a file programmatically to SPDocumentLibrary in SharePoint 2010
using (SPSite site = newSPSite("http://mySharePointServer"))
{
using (SPWeb web = site.OpenWeb())
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPDocumentLibrary documentLib = web.Lists["YourLibraryName"] as SPDocumentLibrary;
Stream fStream = FileUpload1.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 + "/" + FileUpload1.PostedFile.FileName;
bool IsOverwriteFile = true;
SPFile file = documentLib.RootFolder.Files.Add(_fileUrl, _byteArray, IsOverwriteFile);
SPListItem item = file.Item;
item["Title"] = FileUpload1.PostedFile.FileName;
item.Update();
file.Update();
web.AllowUnsafeUpdates = false;
});
}
}
Adding Folder and SubFolder to document library in SharePoint 2010
using (SPSite site = new SPSite("http://mySharePointServer"))
{
using (SPWeb web = site.OpenWeb())
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPDocumentLibrary documentLib = web.Lists["TestLib"] as SPDocumentLibrary;
web.AllowUnsafeUpdates = true;
SPListItem newFolder = documentLib.Items.Add("", SPFileSystemObjectType.Folder,"TestRootFolder");
newFolder.Update();
//Creating Subfolder inside folder
stringsubFolderUrl = web.Url + "/" + newFolder.Url;
SPListItem subFolder = documentLib.Items.Add(subFolderUrl,SPFileSystemObjectType.Folder, "TestSubFolder");
subFolder.Update();
web.AllowUnsafeUpdates = false;
});
}
}
References
http://www.sharepointpals.com/post/Programmatically-upload-and-retrieve-image-from-SharePoint-Picture-Library
No comments:
Post a Comment