Step1: I have created an SPItem in document libray by choosing a file through object model.
Step2: Now i want to replace the existing file of the same SPItem with new file.
How can i achieve this using SP Object model.
Thanks in advance...
use the following function
web--> is the spweb object
URk--> document library url + the filename to be added
content --> byte array object of the file from the file system
true--> if u want to override else false
Hi Varun, thanks for the reply, I have already used this code for the first step of item adding to document library, now in the second time i want to use a different file to be replaced with the existing 1 through SP Object model. we dont have replace method for the Item.File. How can i implement this functionality?
Best Regards, Srikanth Ch
Varun Saxena gave you the correct API call.
web.Files.Add(URL, contents, true );
The boolean value of true tells SharePoint that you want to overwrite the file. Please see http://msdn.microsoft.com/en-us/library/ms412937.aspx
My SharePoint Blog - http://www.davehunter.co.uk/blog
You should be able to overwrite an existing file using Dave's and Srikanth reply. It is as simple as that.
However, to get your existing file name you might want to write a small function to get that
Function GetFileName() as String
Dim currentItem as splistitem = listobj.getitembyID(passthecurrentlistitemid)
MSDN - http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splist.getitembyid.aspx
once you get this you can easily return the file name as string and add that using same file name
See this - http://www.sharepointdevwiki.com/display/public/Accessing+list+items+using+the+object+model
look for 'Accessing List Item Instances'
Note - this is psuedocode and you will have to fit the logic to the programming language you are using
Hope this helps,
Hi all, for the clear explanation...
I have a document/file in a document library. i am getting the listitem reference using SPListItem item = list.GetItemById(listitemID);
now i am using the below code to overwrite existing file with new file
string fn = Path.GetFileName(FileUpload1.PostedFile.FileName);
Stream fStream = FileUpload1.PostedFile.InputStream;
byte contents = new byte[(int)fStream.Length + 1];
fStream.Read(contents, 0, (int)fStream.Length);
SPFolder docFolder = list.RootFolder;
SPFile docFile = docFolder.Files.Add(fn, contents, true);
item = docFile.Item;
But its not replacing/overwriting the file, instead its creating a new entry in the document library. But i want the same doc library item to be updated. Any suggestion.....
Best Regards, Srikanth Ch