R – Getting files and their version numbers from sharepoint

sharepointversioning

As a temporary stopgap until all the designers are in place we are currently hand-cranking a whole bunch of xml configuration files at work. One of the issues with this is file-versioning because people forget to update version numbers when updating the files (which is to be expected as humans generally suck at perfection).

Therefore I figure that as we store the files in Sharepoint I should be able to write a script to pull the files down from Sharepoint, get the version number and automatically enter/update the version number from Sharepoint into the file. This means when someone wants the "latest" files they can run the script and get the latest files with the version numbers correct (there is slightly more to it than this so the reason for using the script isn't just the benefit of auto-versioning).

Does anyone know how to get the files + version numbers from Sharepoint?

Best Solution

There is a way to do it thru web services, but I have done more with implementing custom event handlers. Here is a bit of code that will do what you want. Keep in mind, you can only execute this from the server, so you may want to wrap this up in a web service to allow access from your embedded devices. Also, you will need to reference the Microsoft.SharePoint.dll in this code.

using (SPSite site = new SPSite("http://yoursitename/subsite"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPListItemCollection list = web.Lists["MyDocumentLibrary"].GetItems(new SPQuery());
        foreach(SPListItem itm in list) {
            Stream inStream = itm.File.OpenBinaryStream();
            XmlTextReader reader = new XmlTextReader(inStream);
            XmlDocument xd = new XmlDocument();
            xd.Load(reader);
            //from here you can read whatever XML node that contains your version info
            reader.Close();
            inStream.Close();
        }
    }
}

The using() statements are to ensure that you do not create a memory leak, as the SPSite and SPWeb are unmanaged objects.

Edit: If the version number has been promoted to a library field, you can access it by the following within the for loop above:

itm["FieldName"]
Related Question