2

I have document library name "Test" and want to update the property of documents. If the value of the Title field equals to ABC then it should get updated to XYZ.

I have created console application but is not working.

string _siteUrl = "http://app/sites/test";

using (SPSite site = new SPSite(_siteUrl))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPFileCollection collFile = web.GetFolder("Test/").Files;
        foreach (SPFile fileObj in collFile.Folder.Files)
        {
            SPFile sourcefile = web.GetFile("Test" + "/" + fileObj.Name);
            if (sourcefile.Exists)
            {
                foreach (SPFile file in collFile)
                {
                    SPListItem dstItem = (SPListItem)file.Item;
                    if (dstItem["Title"] == "ABC")
                    {
                        dstItem["Title"] = "XYZ";
                    }
                }
            }
        }
    }
}
  • What's the error you get? – Evariste Jan 22 '16 at 12:40
  • ur code is quite redundant: if you are looping in collFile.Folder.Files there is no need of web.GetFile. Just guessing, your problem is AllowUnsafeUpdates – Marco Jan 22 '16 at 12:43
  • AllowUnsafeUpdates can't be the problem in a console app... But I agree with remarks about nested loops, see my answer. – Evariste Jan 22 '16 at 12:44
0

First of all, I don't understand all your nested loop. Here's a simplified version:

        using (SPSite site = new SPSite(_siteUrl))
        {
            using (SPWeb web = site.OpenWeb())
            {
                    SPFileCollection collFile = web.GetFolder("Test/").Files;
                    foreach (SPFile fileObj in collFile)
                    {
                       SPListItem dstItem = fileObj.Item;
                       if (dstItem["Title"] == "ABC")
                       {
                          dstItem["Title"] = "XYZ";
                          dstItem.Update();
                       }
                    }
            }
        }

But the real problem was most probably that you did not call .Update.

  • Exeption is : you cannot invalidate the SPRequest object while it is in use. I have used update, forget to mention – Brishal Jan 22 '16 at 12:57
  • after resolving exeption also it is not going in foreach loop – Brishal Jan 22 '16 at 13:11
  • 1
    Can you please share your updated version of the code? – Evariste Jan 22 '16 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.