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!
|