scenario :
I want to prevent to add duplicate files to document library in sharepoint . when we are uploading document it will verify the all Doclib Files then if file name is exists it will show alertbox.
I want to prevent to add duplicate files to document library in sharepoint . when we are uploading document it will verify the all Doclib Files then if file name is exists it will show alertbox.
Then I have written some sample code for this issue:
/// <summary>
/// An item is being added.
/// </summary>
public override void ItemAdding(SPItemEventProperties properties)
{
string fileUrl = properties.BeforeUrl;
string fileName = fileUrl.Substring(fileUrl.LastIndexOf('/') + 1);
if (IsExisted(properties.List, fileName))
{
properties.Cancel = true;
properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
properties.RedirectUrl = "/_Layouts/MyEventError.aspx";
}
}
/// <summary>
/// An item is being updated.
/// </summary>
public override void ItemUpdating(SPItemEventProperties properties)
{
string fileUrl = properties.BeforeUrl;
string fileName = fileUrl.Substring(fileUrl.LastIndexOf('/') + 1);
if (IsExisted(properties.List, fileName))
{
properties.Cancel = true;
properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
properties.RedirectUrl = "/_Layouts/MyEventError.aspx";
}
}
private Boolean IsExisted(SPList list, string fileName)
{
bool isExisted = false;
SPQuery query = new SPQuery();
query.Query = string.Format(
"<Where><Eq><FieldRef Name='FileLeafRef'></FieldRef><Value Type='Text'>{0}</Value></Eq></Where>",
fileName);
query.ViewAttributes = "Scope=\"Recursive\"";
SPListItemCollection itemColl = list.GetItems(query);
if (itemColl.Count > 0)
{
isExisted = true;
}
return isExisted;
}


