Sharepoint Exception : “operation is not valid due to the current state of the object”

12 12 2008

I have started recently some Sharepoint development and I was quickly trapped by a common exception that all beginners have been confonted(I presume…) : “operation is not valid due to the current state of the object”. After searching and trying when this error occurs, I have find an answer… but according many source, this exception can depends on many things.
Mine is when you want to update some file attributes within a SPSecurity.RunWithElevatedPrivileges delegate.

Here my code that fails:

        SPFile f = null;

        SPSecurity.RunWithElevatedPrivileges(delegate()

          {

              using (SPWeb web = GetWebFromUrl(siteUrl, false))

              {

 

                  f=web.GetFolder(folderUrl).Files[descriptor.Name];

                  FillFile(descriptor, f);

                  f.Item.Update();

              }

          });

The error occurs when we reach the code f.Item.Update(). All objects are not null and loaded successfully.

So, to avoid that, the code must be written like that:

        SPFile f = null;

        SPSecurity.RunWithElevatedPrivileges(delegate()

          {

              using (SPWeb web = GetWebFromUrl(siteUrl, false))

              {

                  f=web.GetFolder(folderUrl).Files[descriptor.Name];

              }

          });

        FillFile(descriptor, f);

        f.Item.Update();

A simple change.
I have not found more information about the issue but the problem can be solved like that.