I want to prevent users from overwriting items that have the same name. When users add items to a library there is a checkbox indicating files should be overwritten if they have the same name. In this case I want to enforce that on every submit. I am thinking of an event receiver for ItemAdding but it does not seem to fire if you upload the same document a second time. What is the best approach/technique to create this functionality?
3 Answers
This is a tough one as in ItemUpdating Event both BeforeProperties and AfterProperties are null. So it becomes difficult to detect the difference between a file being overwritten vs. a property being edited. I had the same requirement once and I have blogged about it here: http://sharepointnadeem.blogspot.in/2011/12/prevent-duplicate-files-to-be-uploaded.html
I am not sure how reliable this is but I found this to be working very well. This code is placed in the ItemUpdating method.
// This property will be null when users upload a new document
// otherwise a value will be found. Found values indicate
// a meta property was changed on an existing file.
if (properties.AfterProperties["vti_contenttag"] == null)
{
properties.Cancel = true;
properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
properties.RedirectUrl = "/_Layouts/DocOverwriteProhibitor/FileOverwriteError.aspx";
}
I would like to hear comments on this approach on how reliable it is.
You might need to attach to ItemUpdating instead.
-
Yes the ItemUpdating event appears to be a solution. However I need to detect the difference between a file being overwritten vs. a property being edited. Oct 8, 2012 at 17:47
-
You might just need to see if there is anything in the HttpContext.Current.Request.Files ( msdn.microsoft.com/en-us/library/…) Oct 8, 2012 at 18:51