Cannot invoke HTTP DAV request

When using the Client-Side Object Model (CSOM) for SharePoint and you’re trying to create\overwrite a file using binary data, you’d naturally try and use the SaveBinaryDirect method of the File class:

public void SaveFile(Microsoft.SharePoint.Client.ClientContext context, Microsoft.SharePoint.Client.File file,
                     string relativeItemUrl, byte[] fileData)
{
    using (Stream ms = new MemoryStream(fileData))
    {
        File.SaveBinaryDirect(context, relativeItemUrl, ms, true);
    }
}

When using a MemoryStream the following error will more than likely be raised:

Cannot invoke HTTP DAV request. There is a pending query

I’ve had better success using the System.IO.File class to obtain a FileStream object for a physical file, although in my tests this has been rather hit or miss. Sometimes it worked perfectly and others it gave the same HTTP DAV request error.

Even if that did work perfectly, it doesn’t get around the problem of creating a file on the fly not based on one from a FileStream.

The solution to the problem is to bypass the SaveBinaryDirect method and use the FileCreationInformation class instead:

public void SaveFile(Microsoft.SharePoint.Client.ClientContext context, string folderRelativeUrl,
                     string relativeItemUrl, byte[] fileData)
{
    var fci = new FileCreationInformation
    {
        Url = relativeItemUrl,
        Content = fileData,
        Overwrite = true
    };
 
    Microsoft.SharePoint.Client.Folder folder = context.Web.GetFolderByServerRelativeUrl(folderRelativeUrl);
    Microsoft.SharePoint.Client.FileCollection files = folder.Files;
    Microsoft.SharePoint.Client.File file = files.Add(fci);
 
    context.Load(files);
    context.Load(file);
    context.ExecuteQuery();
}

Creating or overwriting files using this method does not raise the HTTP DAV Request error unlike the SaveBinaryDirect method which is susceptible to this.

This entry was posted in CSOM, SharePoint and tagged , . Bookmark the permalink.
0 0 votes
Article Rating
Subscribe
Notify of
guest

Solve the maths problem shown below before posting: *

2 Comments
Inline Feedbacks
View all comments
qqnagaqq

This wont work for files over 2mb.