Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

This question already has an answer here:

i am working on function that deletes a file from Share Point Documents. The function works but it throws exception that file not found.

protected void DeleteFile(string filename, Uri hostWeb)
    {
        using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))
        {
            Web web = clientContext.Web;
            List docs = web.Lists.GetByTitle("Documents");

            Microsoft.SharePoint.Client.File f = web.GetFileByServerRelativeUrl("/Shared Documents/" + filename);
            f.DeleteObject();
            clientContext.Load(f);
            clientContext.ExecuteQuery(); // Delete file here but throw Exception                
            Console.Write("deleted");
        }
    }
share|improve this question

marked as duplicate by RJ Cuthbertson, John Chapman, PirateEric, Robert Lindgren, Benny Skogberg MCSA Jul 10 '13 at 5:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 1

up vote 3 down vote accepted

Try reversing the order of DeleteObject and Load so you get:

protected void DeleteFile(string filename, Uri hostWeb)
    {
        using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity))
        {
            Web web = clientContext.Web;
            List docs = web.Lists.GetByTitle("Documents");

            Microsoft.SharePoint.Client.File f = web.GetFileByServerRelativeUrl("/Shared Documents/" + filename);
            clientContext.Load(f);
            f.DeleteObject();
            clientContext.ExecuteQuery(); // Delete file here but throw Exception                
            Console.Write("deleted");
        }
    }
share|improve this answer
    
Thanks works fine now. –  Sage Shah Jun 6 '13 at 18:40

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