You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SharePoint 2013 C#同步ItemUpdating事件接收器:如何检测附件变更?

Alright, let's walk through building this SharePoint 2013 synchronous event receiver to detect attachment changes during ItemUpdating and update related fields. Here's everything you need to know:

1. Create the Synchronous Event Receiver Project

First, set up your project in Visual Studio:

  • Create a new SharePoint 2013 - Empty Project, choose Farm Solution (sandbox solutions have limitations with HttpContext access needed for attachment detection).
  • Right-click the project > Add > New Item > Select Event Receiver.
  • Choose the target list type (e.g., Custom List), check the ItemUpdating event, and ensure the event is set to Synchronous (this is the default for ItemUpdating, double-check to be safe).
2. Core Logic: Detect Attachment Additions/Deletions

The key is comparing the original attachments (before update) with the changes the user submitted. Here's the full code for the ItemUpdating method:

using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using Microsoft.SharePoint;

namespace SharePointAttachmentEventReceiver.EventReceivers.CustomList
{
    public class CustomListEventReceiver : SPItemEventReceiver
    {
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            base.ItemUpdating(properties);
            // Enforce synchronous execution (default for ItemUpdating, but explicit is safer)
            properties.Status = SPEventReceiverStatus.Continue;

            try
            {
                // Get original attachments from the existing list item (pre-update)
                SPAttachmentCollection originalAttachments = properties.ListItem.Attachments;
                List<string> originalAttachmentNames = originalAttachments.Cast<string>().ToList();

                // Get attachments marked for deletion from the request form
                string deletedAttachments = HttpContext.Current.Request.Form["__SPDeletedAttachments"];
                List<string> deletedAttachmentNames = string.IsNullOrEmpty(deletedAttachments)
                    ? new List<string>()
                    : deletedAttachments.Split(';').ToList();

                // Get newly uploaded attachments from the request files
                HttpFileCollection uploadedFiles = HttpContext.Current.Request.Files;
                List<string> newAttachmentNames = new List<string>();
                for (int i = 0; i < uploadedFiles.Count; i++)
                {
                    HttpPostedFile file = uploadedFiles[i];
                    if (!string.IsNullOrEmpty(file.FileName) && file.ContentLength > 0)
                    {
                        newAttachmentNames.Add(Path.GetFileName(file.FileName));
                    }
                }

                // Check if there are any attachment changes (add or delete)
                bool hasAttachmentChanges = deletedAttachmentNames.Any() || newAttachmentNames.Any();

                if (hasAttachmentChanges)
                {
                    // Update your target fields here
                    // Example 1: Use AfterProperties to set field value (avoids re-triggering ItemUpdating)
                    properties.AfterProperties["AttachmentStatus"] = "Modified";

                    // Example 2: Directly update the list item (use cautiously to prevent loop triggers)
                    // properties.ListItem["AttachmentStatus"] = "Modified";
                    // properties.ListItem.Update();
                }
            }
            catch (Exception ex)
            {
                // Log errors to SharePoint ULS to debug without breaking user updates
                SPDiagnosticsService.Local.WriteTrace(
                    0,
                    new SPDiagnosticsCategory("AttachmentChangeReceiver", TraceSeverity.Unexpected, EventSeverity.Error),
                    TraceSeverity.Unexpected,
                    $"Error detecting attachment changes: {ex.Message}",
                    ex.StackTrace);

                // Optional: Cancel the update with no error message if needed, or let it continue
                // properties.Status = SPEventReceiverStatus.CancelNoError;
            }
        }
    }
}
3. Critical Notes for Implementation
  • Avoid Loop Triggers: Always prefer using properties.AfterProperties to update fields instead of modifying properties.ListItem directly and calling Update(). The latter will re-trigger the ItemUpdating event, causing an infinite loop unless you add additional checks.
  • Permissions: Ensure the SharePoint application pool account has edit permissions on the target list, as event receivers run under this account.
  • Filename Duplicates: SharePoint automatically appends a suffix (e.g., Document(1).docx) to duplicate filenames. If you need precise post-update validation, you could add a check in the synchronous ItemUpdated event, but this isn't required per your original request.
  • Error Handling: Never skip exception handling—unhandled errors will block the user's update operation and show a generic SharePoint error page. Logging to ULS helps you debug issues later.
  • Why Not Asynchronous Events: Asynchronous events (like ItemUpdated with async enabled) run after the list item is saved, which means your field updates would happen after the user's changes are committed. This doesn't meet your requirement of updating fields during the synchronous ItemUpdating trigger.

内容的提问来源于stack exchange,提问作者Kevin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:27:46