Stefan Pienaar
I would love to change the world, but they won't give me the source code

SharePoint, Checking in all documents in a document library

March 20, 2009 11:20 by stefanpienaar

Manually checking in a bunch of files in a SharePoint Document Library is a mission. Create a new console application and paste the code below in your Main method:

* You will need to reference Microsoft.SharePoint.dll which can be found on the server where SharePoint is installed.

** Just remember to change the hardcoded site name (“http://myserver/”) and document library name (“MyDocumentLibrary”) to reflect your own settings.

using (SPSite site = new SPSite("http://myserver/"))
{
    SPWeb web = site.OpenWeb();
 
    foreach (SPList list in web.Lists)
    {
        if (String.Compare(list.Title, "MyDocumentLibrary", true) == 0)
        {
            SPDocumentLibrary docLib = (SPDocumentLibrary)list;
            // Take ownership of all checked out files in the document library
            foreach (SPCheckedOutFile checkedFile in docLib.CheckedOutFiles)
            {
                Console.WriteLine("Taking ownership of " + checkedFile.Url);
                checkedFile.TakeOverCheckOut();
            }
 
            // Check in all checked out files
            foreach (SPListItem item in list.Items)
            {
                SPFile file = null;
                try
                {
                    file = item.File;
 
                    if (file != null)
                    {
                        if (file.CheckOutStatus != SPFile.SPCheckOutStatus.None)
                        {
                            file.CheckIn("Checked in after uploading");
                            file.Update();
                            Console.WriteLine("File checked-in = " + file.Name);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Could not check-in file = " +
                                        file.Name + " : " + ex.Message);
                }
            }
        }
    }
}
 
Console.WriteLine("All documents checked in, press enter to close this application.");
Console.ReadLine();