I am creating .docx file using template of SharePoint Library and uploading it to the library. But I am facing an error while CheckOut()
. Below is my code.
public void UpdateAndCreateFile(SPWeb web)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
string TemplateUrl = string.Empty;
try
{
TemplateUrl = "template path";
}
catch { }
web.AllowUnsafeUpdates = true;
SPList olist = web.Lists["Document Library"];
String url = olist.RootFolder.ServerRelativeUrl.ToString();
string foldername = Convert.ToString("Foldername in document library");
SPFolder newfolder = web.GetFolder(url + "/" + foldername);
if (!newfolder.Exists)
{
SPFolderCollection folders = web.GetFolder(url).SubFolders;
//Create new folder
folders.Add(foldername);
}
SPFile file = null;
file = web.GetFile("Your Document templated full path");
if (file != null)
{
web.AllowUnsafeUpdates = true;
Stream readStream = file.OpenBinaryStream(); //file is SPFile type
SPFile uploadedFile = newfolder.Files.Add(newfolder.Url + @"/" + "NewDocName.docx", readStream, true);
uploadedFile.CheckOut();
SPListItem listitem = uploadedFile.Item;
// Details is mapped in document
listitem["Details"] = "this content will add in document";
listitem.Update();
uploadedFile.Update();
uploadedFile.CheckIn(string.Empty);
web.AllowUnsafeUpdates = false;
}
});
}
catch (Exception ex)
{
// handle exception here
}
}
Where I am going wrong.
Any help would be appreciated.
Thanks