SharePoint Internals – Hristo Pavlov’s Blog

17 June, 2008

Preserving the last “Modified By” when checking in a file

Filed under: SharePoint — Tags: , , , — hristopavlov @ 4:38 am

I’ve heard people saying that you cannot check in a file specifying explicitely who the “Modified By” user should be. Actually this is not true and you can do this easily through the object model using reflection and the code below:

public static void CheckInFileByUser(

    SPFile file,

    string checkinComment,

    SPCheckinType checkinType,

    SPUser modifiedByUser)

{

    MethodInfo mi = typeof(SPFile).GetMethod(

        “CheckIn”,

        BindingFlags.Instance | BindingFlags.NonPublic,

        null,

        new Type[] { typeof(string), typeof(SPCheckinType), typeof(bool), typeof(SPUser) },

        null);

 

    try

    {

        mi.Invoke(

            file,

            new object[] { checkinComment, checkinType, false, modifiedByUser }

        );

    }

    catch (TargetInvocationException invokeEx)

    {

        throw invokeEx.InnerException;

    }

}

Before calling this code you should check-out the file. If you don’t do so it will rethrow the “The file …. is not checked out.” SPException which will be thrown by SharePoint. The code will also bring all other SharePoint exceptions to you. And of course if you want to preserve the last “Modified By” user when updating your file using this function, just pass the file.ModifiedBy as the user argument retrieved before the file was checked out.

4 Comments »

  1. [...] Preserving the last “Modified By” when checking in a file [...]

    Pingback by Links (6/17/2008) « Steve Pietrek - Everything SharePoint — 18 June, 2008 @ 1:35 am

  2. Hello Hristo,

    Excellent code! I’ve been looking for a way to preserve the ModifiedBy field for ages, since it kept changing into the user running the code all the time. I had almost given up… but this code works fine! :)

    It’s of very good use if you have to manually copy or move a file between sites while maintaining its version history and metadata.

    Thank you very much for this post!

    Ed

    Comment by @ Zele — 26 June, 2008 @ 8:00 am

  3. Ah, quite fascinating, that reflection magic. It always seems when poking with Reflector that there are all sorts of things that might be easier if you could just call some of SharePoint’s private methods. Anyway, this is good stuff and fixed up a point of contention very nicely. Thanks!

    Comment by Chris — 21 July, 2008 @ 9:38 pm

  4. Hey Hristo!

    Fantastic! Very nice Snippet! Thank you! You are my savior! :-)

    Philip

    Comment by Philip — 29 October, 2008 @ 9:57 am


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.