SPListitem.File.Versions – System.Argument.Exception

SPListitem.File.Versions – System.Argument.Exception

I was writing some code yesterday to loop through the list items in a SharePoint list and then loop through each version of the SPListItem’s underlying file.

Here is the code I was using -

[code lang="csharp"]

using (SPSite site = new SPSite("http://theserver"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["The List"];
SPView view = list.Views[new Guid("D9E7BDDC-4C77-4386-BA0E-A786D58EE199")];
SPListItemCollection itemCol = list.GetItems(view);
foreach (SPListItem item in itemCol)
{
foreach (SPFileVersion version in item.File.Versions)
{
string url = version.Url;
}
}
}
}

[/code]

When the code hit the ‘item.File.Versions’ collection it threw a System.Argument.Exception. This really stumped me and I couldn’t figure out at all while the collection was throwing this exception.

After a lot of researching I found this blog post -

http://www.mtelligent.com/journal/2007/10/17/the-insanity-of-getting-versions-of-a-multilinetext-box-set-.html

In this post, David talks about getting the same exception when he is trying to access the list item’s file versions. If you scroll down and look at the comments you you will see that this only seems to be a problem if you are getting the SPListItem as the result of an SPQuery (in my case the spquery is actually an SPView).

This is most likely because getting the item using an SPQuery returns the list item with a minimum amount of data, therefore the versions are not accessible.

The solution here is to create another instance of the SPListItem by using the GetItemById() method which will return all the properties for the list item. This way the SPListItem.File.Versions collection will be accessible and we can iterate through it.

See the correct code -
[code lang="csharp"]
using (SPSite site = new SPSite("http://theserver/"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["The List"];
SPView view = list.Views[new Guid("D9E7BDDC-4C77-4386-BA0E-A786D58EE199")];
SPListItemCollection itemCol = list.GetItems(view);
foreach (SPListItem item in itemCol)
{
//Get a reference to the item again by the ID
SPListItem theItem = list.GetItemById(item.ID);
//The versions collection should now be populated (if versions are available) and no exception should be thrown
foreach (SPFileVersion version in theItem.File.Versions)
{
string url = version.Url;
}
}
}
}
[/code]
Hope this helps someone! :-)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">