1

I'm trying to update SPFile properties.

Here is my code:

            using (SPSite oSite = new SPSite(sFileURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    oWeb.AllowUnsafeUpdates = true;
                    oFile = oWeb.GetFile(sFileURL); 
                    foreach (XmlNode xNode in oXmlDoc.FirstChild.ChildNodes)
                    {
                        oFile.Item.Properties[xNode.Name] = xNode.InnerText;
                        string itemmm =oFile.Item.Properties[xNode.Name].ToString();

                    }
                    oFile.Update();
                    oWeb.AllowUnsafeUpdates = false;
                }
            }

The problem is that when I check the file properties in SharePoint I don't see the changes I have made. I was trying to add AllowUnsafeUpdates = true but it didn't solve the problem.

What else can I do?

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
Guid2015
  • 57
  • 11

2 Answers2

2

In fact, you don't modify SPFile instance, but the associated SPItem. Hence calling SPFile.Update() does nothing. It's better to work with the SPItem instance directly:

SPItem item = oFile.Item;
item.Properties[xNode.Name] = xNode.InnerText;
item.Update();

Also, AllowUnsafeUpdates property is not relevant to your situation. Do not alter it.

Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
2

Your code is lacking all checks which is to be done before actual update.

 using (SPSite oSite = new SPSite(sFileURL))
      {
       using (SPWeb oWeb = oSite.OpenWeb())
            {
             oWeb.AllowUnsafeUpdates = true;
             SPFile oFile = oWeb.GetFile(sFileURL); 
             if (oFile == null)
             {
             return false;
             }
             SPListItem item = oFile.GetListItem();           

             if (item.File.Level == SPFileLevel.Checkout)
             {
                 item.File.UndoCheckOut();
             }
             if (item.File.Level != SPFileLevel.Checkout)
             {
             item.File.CheckOut();
             }

             item["Your Column name"] = "Value";

             item.SystemUpdate(false);
             item.File.CheckIn("SystemCheckedin");
             item.File.Publish("SystemPublished");    
             oWeb.AllowUnsafeUpdates = false;
       }
   }
Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42
  • While you are generally right with the checks, it's not the core of the problem. Btw. there's no need for `SystemUpdate()` in this case. Also, checkin/checkout in case this functionality is not enabled on the document library is superfluous. – Ondrej Tucny Dec 14 '15 at 15:56
  • 1
    @OndrejTucny agreed..but OP is not telling details of error if any.Only saying changes not reflected..This is a working code so thought of sharing – Navoneel Talukdar Dec 14 '15 at 15:59
  • The bug is apparent from the example code provided by the OP. – Ondrej Tucny Dec 14 '15 at 16:01