Updating SPFile properties using SPFile.Update()

2.5k views Asked by At

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?

2

There are 2 answers

0
Ondrej Tucny On BEST ANSWER

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.

3
Navoneel Talukdar On

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;
       }
   }