I have written an event handler at the request of one of my users to provide the
following functionality:
When they upload files to a specific document library they will be using a
specific 16 character file name for each employee. There could be multiple
records for each employe that need to added. So if the filename already exists
in the document library they want to add an extension onto the 16 character file
name. So, a group of files for one employee could be as follows:
Initial file = 16 character filename
Second file = 16 character filename + _1
Third file = 16 character filename + _2
etc...
This is my first time writing an event handler and using C#. I was hoping
someone that has experience with event handlers wouldn't mind taking a look at
my code below to tell me if I'm on the right track.
public override void ItemAdding(SPItemEventProperties properties)
{
//Declare variables.
string strName = string.Empty;
string strNameSplit = string.Empty;
int intcount = 0;
string strNewName = strName + "_" + intitemcount.ToString;
//Look to see if the filename of the uploaded file already exists
foreach (DictionaryEntry entry in properties.AfterProperties)
{
if (entry.Key.Equals("Name"))
{
strName = entry.Value.ToString();
strNameSplit = strName.Substring(0, 16);
}
}
SPList list = properties.OpenWeb().Lists[properties.ListId];
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='" +
list.Fields["Name"].InternalName + "' /><Value Type='Text'>" + strNameSplit +
"</Value></Eq></Where>";
if (list.GetItems(query).Count > 0)
//If filename already exists add the count value + 1 to the end of
the filename.
{
intitemcount = list.GetItems(query).Count + 1;
list.Fields["Name"].InternalName.ToString = strNewName;
ItemAdding.update;
}
}
}
}