Last active
September 7, 2020 16:08
-
-
Save tiagoduarte/0b7da5924aacb8bb24a65267c3556661 to your computer and use it in GitHub Desktop.
Release SharePoint document lock through server side code (C#)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SPList list = web.Lists[txtListTitle.Text]; | |
SPListItem item = list.GetItemById(int.Parse(txtItemID.Text)); | |
SPFile file = item.File; | |
if (file.LockType == SPFile.SPLockType.None) | |
{ | |
txtOutput.Text = "File is not locked"; | |
} | |
else | |
{ | |
int lockUserID = file.LockedByUser.ID; | |
string lockId = file.LockId; | |
SPUser user = web.AllUsers.GetByID(lockUserID); | |
try | |
{ | |
web.AllowUnsafeUpdates = true; | |
//no one but the user him/herself can release an exclusive lock | |
//http://blog.aspjava.com/2016/06/sharepoint-unlock-file-that-is.html | |
using (SPSite userSite = new SPSite(txtWebUrl.Text, user.UserToken)) | |
{ | |
using (SPWeb userWeb = userSite.OpenWeb()) | |
{ | |
SPList userList = userWeb.Lists[txtListTitle.Text]; | |
SPListItem userItem = userList.GetItemById(int.Parse(txtItemID.Text)); | |
SPFile userFile = userItem.File; | |
userWeb.AllowUnsafeUpdates = true; | |
userFile.ReleaseLock(lockId); | |
} | |
} | |
txtOutput.Text = "Lock released!"; | |
} | |
catch (Exception ex) | |
{ | |
txtOutput.Text = "Error: " + ex.Message; | |
} | |
finally | |
{ | |
web.AllowUnsafeUpdates = false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment