3

I'm developing a WebPart in SharePoint 2007 and sometimes when I try to delete a file from Document Library with code like this:


SPWeb web = SPControl.GetContextWeb(WebPart.WebPartContext);

SPList list = web.GetList(web.Site.Url + "/ListName");

SPFile file = list.GetItemByUniqueId(new Guid(fileId)).File;

file.Delete();

I get following Exception:

Cannot remove file "filename.bmp". Error Code: 3604.

Stack Trace: at Microsoft.SharePoint.Library.SPRequest.AddOrDeleteUrl(String bstrUrl, String bstrDirName, Boolean bAdd, UInt32 dwDeleteOp, Int32 iUserId, Guid& pgDeleteTransactionId) at Microsoft.SharePoint.SPFile.DeleteCore(DeleteOp deleteOp) at Microsoft.SharePoint.SPFile.Delete()

The SPFile object is not null.

Any ideas why that's happening?

igorti
  • 3,828
  • 3
  • 22
  • 29

2 Answers2

0

The only possible thing I can think of is that the file is currently checked out or locked for editing by another user. Try this...

SPWeb web = SPControl.GetContextWeb(WebPart.WebPartContext);
SPList list = web.GetList(web.Site.Url + "/ListName");
SPFile file = list.GetItemByUniqueId(new Guid(fileId)).File;

if (file.CheckOutStatus != SPFile.SPCheckOutStatus.None)
{
  file.UndoCheckOut();
  file.CheckOut();
}

file.Delete();
Fraser
  • 15,275
  • 8
  • 53
  • 104
  • Thanks for suggestion. I have tried code above and CheckOutStatus is None when I'm getting exception. It works well to delete file in SharePoint web interface, but not with API. – igorti Sep 08 '10 at 15:03
0

Are you deleting a file from a document library?

If so, you need delete whole item, because document library item cannot exist without a file. So you need to change your code this way:

SPWeb web = SPControl.GetContextWeb(WebPart.WebPartContext);
SPList list = web.GetList(web.Site.Url + "/ListName");
// delete whole item
SPListItem itemToDelete = list.GetItemByUniqueId(new Guid(fileId));
itemToDelete.Delete();

Hope it helps!

Andrey Markeev
  • 1,344
  • 15
  • 20