咨询:如何检测SharePoint文件是否被其他用户打开及Azure函数实现方案
原PnP/JS的getLockedByUser()仅能识别当前用户的独占锁定,无法检测其他用户打开文件时创建的共享锁定,以下三种方案可解决该问题:
一、SharePoint REST API 实现
通过LockInfo端点获取文件所有类型的锁定信息(包括其他用户的共享锁定):
// SPFx中使用SPHttpClient调用示例 const fileRelativeUrl = "/sites/your-site/Documents/target-file.docx"; const apiUrl = `${this.context.pageContext.web.absoluteUrl}/_api/web/getfilebyserverrelativeurl('${fileRelativeUrl}')/LockInfo`; this.context.spHttpClient.get(apiUrl, SPHttpClient.configurations.v1) .then(res => res.json()) .then(data => { // LockType:0=无锁定,1=独占锁定,2=共享锁定 if (data.LockType !== 0) { console.log(`文件被 ${data.LockedByUser.Title} 锁定,类型:${data.LockType === 1 ? '独占' : '共享'}`); } else { console.log("文件未被任何用户锁定"); } });
二、Microsoft Graph API 实现
调用Graph的文件详情端点,通过file.lock属性获取跨用户锁定状态:
// SPFx中使用GraphHttpClient调用示例 const siteId = this.context.pageContext.site.id.toString(); const itemId = "your-file-item-id"; // 可通过文件ListItemId转换或Graph查询获取 const apiUrl = `https://graph.microsoft.com/v1.0/sites/${siteId}/drive/items/${itemId}`; this.context.graphHttpClient.get(apiUrl, GraphHttpClient.configurations.v1) .then(res => res.json()) .then(data => { if (data.file?.lock) { const lockInfo = data.file.lock; console.log(`文件被 ${lockInfo.owner.displayName} 锁定,类型:${lockInfo.type}`); } else { console.log("文件未被任何用户锁定"); } });
三、Azure函数(C#)实现
使用PnP Core SDK在后端获取锁定信息,适合多站点权限统一管理场景:
using PnP.Core.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log) { string siteUrl = req.Query["siteUrl"]; string fileRelativeUrl = req.Query["fileRelativeUrl"]; // 初始化PnP上下文(需配置应用权限) var authProvider = new ClientSecretAuthenticationProvider("{client-id}", "{client-secret}", "{tenant-id}"); using var context = await PnPContextFactory.CreateAsync(siteUrl, authProvider); var file = await context.Web.GetFileByServerRelativeUrlAsync(fileRelativeUrl, p => p.LockInfo); return file.LockInfo.LockType != LockType.None ? new OkObjectResult(new { IsLocked = true, LockedByUser = file.LockInfo.LockedByUser.Title, LockType = file.LockInfo.LockType.ToString() }) : new OkObjectResult(new { IsLocked = false }); }
注意事项
- 共享锁定由Office客户端/网页端打开文件时自动创建,关闭文件后会延迟释放;
- 权限要求:REST需站点读取权限,Graph需
Files.Read/Sites.Read.All权限,C#应用需AllSites.Read类权限。
内容的提问来源于stack exchange,提问作者Ofer Gal
相关产品推荐
相关产品推荐

