How to prevent Files with same Name?
-
29-09-2020 - |
Question
I have a service that takes a file from a library and send it to an already specified folder.
This becomes a problem when I'm having files with same names on diferent folders.
Lets say that the event sends files to folder X, and I have fileA on folder A and also a fileA but this one on folder B.
What happens is that the folder X will recieve the first fileA, and then will replace the first one with the second!
I'm trying to do it as a ItemAdding event to change the file name on folder X so I can have the 2 files on this folder. Possibly fileA and fileA_2.
But how can I get the file that is being moved, if properties.ListItem
returns null?
thanks!
edit: here is the code I was trying to do:
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
if (properties.ListItem != null && properties.ListItem["Name"] != null)
{
SPListItem currItem = properties.ListItem;
string oldName = currItem["Name"].ToString();
foreach (SPListItem item in properties.ListItem.ParentList.Items)
{
if (item.Name.Equals(oldName))
{
currItem["Name"] += "_1";
properties.Web.AllowUnsafeUpdates = true;
EventFiringEnabled = false;
currItem.SystemUpdate();
properties.Web.AllowUnsafeUpdates = false;
EventFiringEnabled = true;
break;
}
}
}
}
Solution
You can get URL of the file being added with properties.AfterUrl
in ItemAdding
event.
EDIT:
Check whether the specified file exists and if the file already exists cancel the event. That's the best you can do in ItemAdding
event AFAIK.