DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

Change created by,modifed by,created and modified values of a file programatically in SharePoint

By Ashok Nalam on 03 Jan 2013 | Category: Sharepoint | Tagged: file 
The snippet covers how to Change created by,modifed by,created and modified values of a file programatically in SharePoint.
  Discuss Add Comment   |  
Add rating Rate this resource   
In some scenario's while uploading a file to share point library we need to change the  created by,modifed by,created and modified values. If you try to upload document directly, it shows current user name for createdby/modifiedby fileds and current datetime for created/modified fileds.
static void Main(string[] args)
{
string uploadFile = @"C:\SampleFile.txt";
string siteURL = "http://YourSharepointsiteURL";
string docLibraryName = "Shared Documents";

using (SPSite objSite = new SPSite(siteURL))
{
using (SPWeb objWeb = objSite.OpenWeb())
{
if (!System.IO.File.Exists(uploadFile))
throw new FileNotFoundException("File not found.", uploadFile);

SPFolder myLibrary = objWeb.Folders[docLibraryName];

bool replaceExistingFiles = true;
string fileName = System.IO.Path.GetFileName(uploadFile);
SPUser user = objWeb.EnsureUser("username");
//For "Created By" and " Modified By" the values are stored in format "ID;#LoginName", so create the same format
string userIDHashName = user.ID + ";#" + user.Name;

FileStream fileStream = File.OpenRead(uploadFile);
// add document to library
SPFile spfile = myLibrary.Files.Add(fileName, fileStream,replaceExistingFiles);
spfile.Item["Created"] = DateTime.Now.AddDays(-1);
spfile.Item["Modified"] = DateTime.Now.AddDays(-2);
spfile.Item["Created By"] = userIDHashName;
spfile.Item["Modified By"] = userIDHashName;

// update libary
spfile.Item.Update();
// update libary
myLibrary.Update();

}
}
}

Note: The username user should exsists in site users otherwise if you provide  invalid user for Created By/Modifed By we will get exception.
Hope this works!

  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9226  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.
 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys