Click here to Skip to main content
14,774,692 members
Articles » Enterprise Systems » SharePoint Server » General
Posted 19 Jul 2010


18 bookmarked

Force SharePoint Document Unlocked / Checked In

Rate me:
Please Sign up or sign in to vote.
4.93/5 (8 votes)
8 Mar 2013CPOL
Forces a checked out / locked document to be unlocked, even short-term locks.



SharePoint places locks on files in document libraries when you check them out or open them. Sometimes the user's PC crashes, or they lose their internet connection, or solar flares hit the server room, and the lock cannot be released no matter how hard an admin tries. SharePoint calls this the CheckOutStatus which, for this article, I will call a lock since that is effectively what the status is describing.

Some have already written code in a console application to force a check-in of the document. But it only works for long-term locks (check outs). A short-term lock is placed on the document when it's not checked out but the client application is locking it. If, for reasons explained in the Background section, the short-term lock isn't released, you either have to reboot the server or wait until the lock's expiration.

The client application might renew the checkout's expiration time; for example, Office programs renew locks in 10 minute intervals. If the client program doesn't renew the lock, SharePoint is supposed to release it. However, if the client application crashes or a couple other scenarios play out, people end up waiting hours or even days for their document to be unlocked. And to my knowledge, there is no way to unlock a short-term lock through the API (probably by design).

Using this application, you can unlock long-term and short-term locks quickly and easily.


You may want to read this blog post on SharePoint lock types. It does a great job of describing checkout statuses and when they're applied.

A word on short-term locks:

Sometimes when trying to check out a document, they will get an error saying "The file [filename] is checked out or locked for editing by [username]"; if your authentication cookie expired, sometimes [username] is you! This error is well documented by Microsoft here, but the only workaround is to sit and wait for SharePoint to unlock it, which is supposed to take 10 minutes, but sometimes takes hours or days!

As explained in the KB article, this happens when you try to edit the document in the client program and then the program crashes. Also, I've found that this happens when using WebDAV (Explorer) view to open documents without checking them out. It can also happen through the web site if you don't check out the document before editing it.

Normally, you can close the client application and the short-term lock gets released, but sometimes, especially if authentication cookies expire or the application crashes, there are problems, and the lock isn't released. Or maybe that naughty user opened the document without checking it out and then went to lunch, then there's no way to force it free if you can't get into their computer! Even powering off the computer doesn't work sometimes.

I've seen this cause strange things. When you try to check out a document, you might get an error saying "The file [filename] is not checked out."!! Well duh, that's why I'm trying to check it out...I don't fully understand that one, but I think SharePoint is trying to check out the document, realizes it has a CheckOutStatus of ShortTerm, and instead tries to check it in (speculation).

Using the Code

You must run this code from the SharePoint server since it uses the SharePoint object model and not Web Services. When you open the program, you just enter the URL of the site, including the site collection, the name of the document library (as shown in the URL, not the display name), the full file name of the document, and click "Find" to find the document and get the checkout status information on it.

Here's the code:

private void FindButton_Click(object sender, EventArgs e)
    this.StatusField.Text = "Searching..." + Environment.NewLine;
    this.LockStatusField.Text = string.Empty;
        Uri siteUri = new Uri(this.SiteUrlField.Text.Trim());
        using (SPWeb web = new SPSite(siteUri.ToString()).OpenWeb())
            bool libraryFound = false;
            foreach (SPList list in web.Lists)
                if (list.BaseType == SPBaseType.DocumentLibrary && string.Equals(
                    list.RootFolder.Url, this.libraryField.Text.Trim(),
                    libraryFound = true;
                    this.statusField.Text += "Found library. Searching for document..." +

                    SPQuery NameQuery = new SPQuery();
                    NameQuery.Query = 
                        "<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='File'>" +
                        this.filenameField.Text.Trim() + "</Value></Eq></Where>";
                    NameQuery.RowLimit = 1;
                    if (recursiveField.Checked)
                        NameQuery.ViewAttributes = @"Scope=""Recursive""";
                    if (recursiveAllField.Checked)
                        NameQuery.ViewAttributes = @"Scope=""RecursiveAll""";
                    if (!string.IsNullOrEmpty(folderNameField.Text.Trim()))
                            SPFolder parentFolder = list.ParentWeb.GetFolder(
                                siteUri.ToString() + "/" + list.RootFolder.Url + "/" +
                            this.statusField.Text += "Found folder." + Environment.NewLine;
                            NameQuery.Folder = parentFolder;
                        catch (Exception)
                            this.statusField.Text += "Could not find folder: '" +
                               siteUri.ToString() + "/" + list.RootFolder.Url + "/" +

                    SPListItemCollection documents = list.GetItems(NameQuery);
                    if (documents.Count > 0 && documents[0].Name.ToLower() == 
                        SPListItem item = documents[0];
                        this.statusField.Text += "Found document at: '" + item.Url + "'" +


                        if (item.File.CheckOutStatus != SPFile.SPCheckOutStatus.None)
                            this.unlockButton.Enabled = true;
                            this.unlockButton.Enabled = false;
                        itemToUnlock = item;
                        statusField.Text += "Could not find document: '" + 
                            this.filenameField.Text.Trim() + "'.";

            if (libraryFound == false)
                StatusField.Text += &quot;Could not find library: '&quot; + 
                                    this.LibraryField.Text.Trim() + &quot;'.&quot;;
    catch (Exception ex)
        StatusField.Text += Environment.NewLine + &quot;Error occurred. Details: &quot; + 
            Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace;

It finds the SPWeb from the URL, loops through all the lists in the web (I've found looping is faster than using GetList()), builds a CAML query to find the document, and if the document is found, it reports the checkout status information on it.

The "Unlock" button does different things depending on whether it's a long-term or short-term lock. If it's a long-term lock, it just forces the document to be checked back in. If it's a short-term lock, it has to go to the content database.

Disclaimer: Directly modifying the SharePoint content database is not recommended or supported by Microsoft (but works well in this case).

If the file has a short-term lock, the only solution I could find to release it is by directly modifying the content database. It does a simple update to the CheckoutExpires column in the AllDocs table for the SharePoint document:

private void UnlockButton_Click(object sender, EventArgs e)
    if (itemToUnlock == null)
        this.StatusField.Text += "No file to unlock!" + Environment.NewLine;

    this.StatusField.Text = "Unlocking..." + Environment.NewLine;

    if (itemToUnlock.File.CheckOutStatus == SPFile.SPCheckOutStatus.ShortTerm)
        if (string.IsNullOrEmpty(itemToUnlock.UniqueId.ToString()))
            StatusField.Text += "File has a short-term lock and " + 
                                "UniqueId cannot be determined for database update.";

        StatusField.Text += "Unsupported and not recommended WARNING." + Environment.NewLine;
        string message = "WARNING!! The selected file has a short-term " + 
                         "lock on it. It should be released in 10 minutes. " +
                         "You can force the item to be unlocked by setting " + 
                         "the checkout to expire immediately in the content database. " +
                         "Modifying the database is not supported by Microsoft " + 
                         "and is not recommended. Do you wish to cancel?";
        if (MessageBox.Show(message, "WARNING", 
            MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, 
            MessageBoxDefaultButton.Button1) == DialogResult.No)
            catch (Exception ex)
                StatusField.Text += Environment.NewLine + 
                    "Error occurred. Details: " +
                    Environment.NewLine + ex.Message + 
                    Environment.NewLine + ex.StackTrace;

            StatusField.Text += "Database updated. File should now be unlocked.";
            // wait 2 seconds for the file to get unlocked
    else if (itemToUnlock.File.CheckOutStatus != SPFile.SPCheckOutStatus.None)
    { // long-term lock, check it in manually
            itemToUnlock.File.CheckIn("Forced Checkin");

            this.StatusField.Text += "File checked in." + Environment.NewLine;
        catch (Exception ex)
            StatusField.Text += Environment.NewLine + "Error occurred. Details: " +
                Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace;
        this.StatusField.Text += "File doesn't have a lock." + Environment.NewLine;

    if (itemToUnlock.File.CheckOutStatus == SPFile.SPCheckOutStatus.None)
        this.UnlockButton.Enabled = false;

Here's the code to update the content database:

private void UpdateItemCheckoutExpiration(SPListItem item)
    SqlConnection contentDatabaseConnection = null;
        contentDatabaseConnection = new SqlConnection(

        string UpdateCommandText = string.Format("UPDATE dbo.AllDocs SET " + 
               "CheckoutExpires = '{0:yyyy-MM-dd HH:mm:ss:fff}' WHERE Id = '{1}'", 
               DateTime.Now.ToUniversalTime(), item.UniqueId.ToString());
        SqlCommand UpdateCommand = new SqlCommand(UpdateCommandText, 
        SqlDataAdapter contentDataAdapter = new SqlDataAdapter();
        contentDataAdapter.UpdateCommand = UpdateCommand;
    catch (Exception)
        if (contentDatabaseConnection != null && 
                 contentDatabaseConnection.State != ConnectionState.Closed)

Points of Interest

Microsoft's recommendation to simply "wait 10 minutes" for the this error to be fixed is ridiculous, and many times doesn't work. I've spent nearly an entire day looking for ways to fix this, and I hope I save someone out there the frustration and time on this one.


  • First release.
  • Updated 10-28-10: Added recursive controls and tweaked code to recursively search folders in a document library. Added ability to search a specific folder for files.
  • Updated 06-14-2012: Added exception handling to ReportItemCheckoutStatus to handle stupid SharePoint exceptions when trying to call CheckedOutDate.
  • Updated 03-08-2013: Fixed a bug trying to search for a site with spaces in the URL. Added a manifest to request UAC elevation if UAC is enabled (fixes a security error if run without administrator privileges).


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer Veracity
United States United States
I'm a .NET developer, fluent in C# and VB.NET with a focus on SharePoint and experience in WinForms, WPF, Silverlight, ASP.NET, SQL Server. My roots come from a support/system administrator role so I know my way around a server room as well.

I have a passion for technology and I love what I do.

Comments and Discussions

GeneralRe: "Unhandled exception has occurred in your application" error Pin
Valerygata11-Jun-12 22:03
MemberValerygata11-Jun-12 22:03 
GeneralRe: "Unhandled exception has occurred in your application" error Pin
jabit12-Jun-12 6:31
Memberjabit12-Jun-12 6:31 
GeneralRe: "Unhandled exception has occurred in your application" error Pin
Valerygata12-Jun-12 23:29
MemberValerygata12-Jun-12 23:29 
GeneralRe: "Unhandled exception has occurred in your application" error Pin
jabit13-Jun-12 8:51
Memberjabit13-Jun-12 8:51 
GeneralRe: "Unhandled exception has occurred in your application" error Pin
Valerygata14-Jun-12 0:20
MemberValerygata14-Jun-12 0:20 
GeneralRe: "Unhandled exception has occurred in your application" error Pin
jabit14-Jun-12 7:32
Memberjabit14-Jun-12 7:32 
GeneralRe: "Unhandled exception has occurred in your application" error Pin
Valerygata14-Jun-12 23:09
MemberValerygata14-Jun-12 23:09 
QuestionNot understanding the status message Pin
Todd Crenshaw9-Apr-12 8:03
MemberTodd Crenshaw9-Apr-12 8:03 
I have exactly what you've described happening in a document library (SharePoint Enterprise 2010 SP1). Any document added to the document library becomes locked. I can't delete the document library. When I run your tool it locates and identifies the file without any problem. The strange part is that all the files are locked by "System Account" and at the exact time the file access attempt is made.

Checkout status: LongTerm
Checked out by: System Account
Checked out on: 4/9/2012 11:27:32 AM

Upon attempting to unlock, the status returns:


Error occurred. Details:
This item cannot be updated because it is locked as read-only.
at Microsoft.SharePoint.SPFile.CheckIn(String comment, SPCheckinType checkInType, Boolean bIsMigrate, SPUser modifiedBy)
at Microsoft.SharePoint.SPFile.CheckIn(String comment)
at ForceSPItemUnlock.UnlockerForm.UnlockButton_Click(Object sender, EventArgs e)

I've not been able to find anything more about this problem on the Internet and am just about ready to call Microsoft, though I'm not confident they will provide the help needed. Thank you for anytime you may spend trying to figure this one out. It's driving me crazy, especially since it's not on a critical site but the site owner thinks it is if you know what I mean. Still, if this problem occurs on a critical site, it would be nice to be able to resolve it.

Todd Crenshaw
AnswerRe: Not understanding the status message Pin
jabit9-Apr-12 10:34
Memberjabit9-Apr-12 10:34 
Questionhttps Pin
lodbroktest0121-Dec-11 3:56
Memberlodbroktest0121-Dec-11 3:56 
QuestionRe: https Pin
jabit21-Dec-11 4:20
Memberjabit21-Dec-11 4:20 
GeneralMy vote of 5 Pin
glenn.horton@freemanco.com2-Nov-10 6:23
Memberglenn.horton@freemanco.com2-Nov-10 6:23 
GeneralRe: My vote of 5 Pin
jabit2-Nov-10 9:38
Memberjabit2-Nov-10 9:38 
GeneralThanks You are good Pin
insasy1-Nov-10 3:58
Memberinsasy1-Nov-10 3:58 
GeneralRe: Thanks You are good Pin
jabit2-Nov-10 9:39
Memberjabit2-Nov-10 9:39 
GeneralMy files live in a folder inside the documemt Library Pin
insasy26-Oct-10 15:32
Memberinsasy26-Oct-10 15:32 
GeneralRe: My files live in a folder inside the documemt Library Pin
jabit27-Oct-10 5:55
Memberjabit27-Oct-10 5:55 
GeneralRe: My files live in a folder inside the documemt Library Pin
jabit28-Oct-10 8:41
Memberjabit28-Oct-10 8:41 
GeneralMy vote of 4 Pin
wd6015227-Jul-10 12:06
Memberwd6015227-Jul-10 12:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.