There are 2 ways to upload files to SharePoint 2010 document libraries using managed client object model.
The first method uses a client library batch mechanism. It will encode the binary using BASE64 encoding, which could increase the message size by one third. There might be problems if this isn’t configured correctly. An example of this code is below:
1: ClientContext context = new ClientContext("http://spdevinwin");
2:
3: Web web = context.Web;
4:
5: FileCreationInformation newFile = new FileCreationInformation();
6: newFile.Content = System.IO.File.ReadAllBytes(@"C:\Work\Files\17580_FAST2010_S05_Administration.pptx");
7: newFile.Url = "17580_FAST2010_S05_Administration 4MB file uploaded via client OM.pptx";
8:
9: List docs = web.Lists.GetByTitle("Documents");
10: Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
11: context.Load(uploadFile);
12: context.ExecuteQuery();
13: Console.WriteLine("done");
The above code might fail throwing a (400) Bad Request error depending on the file size. The following code is used to set a higher limit to the upload size. Note: This is not the same as the max. file size upload limit option available in the web application settings.
1: SPWebService ws = SPWebService.ContentService;
2: SPClientRequestServiceSettings clientSettings = ws.ClientRequestServiceSettings;
3: clientSettings.MaxReceivedMessageSize = 10485760;
4: ws.Update();
5: Console.WriteLine(clientSettings.MaxReceivedMessageSize);
The above code sets the message batch size to 10MB so that larger files can be uploaded using managed client object model.
The second methods uses HTTP DAV and sends raw binary across the wire and does not increase the message size. It is also the preferred upload method when using managed client object model. Here’s a sample:
2: using (FileStream fs = new FileStream(@"C:\Work\Files\17580_FAST2010_S03_Arch.pptx", FileMode.Open))
3: {
4: Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, "/documents/17580_FAST2010_S03_Arch from client OM.pptx", fs, true);
5: }
Hope this helps! Stay tuned for most posts on managed client object model.
Hi Sridhara,
Really excellent article. It helped me a lot.
I am using the second method(i.e. using FileStream object) to upload files. I am using multiple threads to upload files to same or different libraries in sharepoint 2010 from my win application. I am getting following errors sometimes:
1. Cannot invoke HTTP DAV request. There is a pending query.
2. The remote server returned an error: (409) Conflict.
Can you please let me know the root cause for these and any workaround possible for these issues?
Thanks in advance.
Hi Sridhara
Thanks for this article. It help me alot
@am20an if you still face the problem or anybody else is having
then here is the solution which work for me
ClientContext ctx = new ClientContext("http://yoursharepointURL");
Web currentWeb = ctx.Web;
ctx.Load(currentWeb);
ctx.ExecuteQuery();
using (FileStream fs = new FileStream(@"C:\data\TestFile.pptx", FileMode.Open))
{ Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, "/Sample Documents/TestFile from client.pptx", fs, true);
}
Console.WriteLine("Uploaded File Successfully");
and be sure the "http://yoursharepointURL/Sample Documents" is a valid path where you want to upload the file.
Hope this work for you too.
Thanks & Regards
Reetika Tomer
(MCTS - .Net Framework 2.0, Web Applications)
Sr. Software Engineer
Daffodil Software Ltd
Gurgaon (HR)
India
thanks for example code!
It works fine on the server-machine, but using a other system in the network the method "SaveBinaryDirect" throw an exception ("The underlying connection was closed: A connection that was expected to maintain their closed down the server").
My activedirectory user has full permission for the site.
I think it isn't a permission problem, because all other functions for example read items or updating items works fine.
Only the method SaveBinaryDirect() throw an exception.
Do you know this error? I hope you can help me.
Best regards!
Sven
Hey is there anyway to attach meta data to the document during upload )with either method)? or do you have to come back and do it after?
Hi, I too am having problems uploading files using SaveBinaryDirect. I keep getting an error HTTP DAV, the same as am20an. Have you a solution for this?
Kind regards
@Blaithin please forgive the asking of potentially stupid questions, I'm just trying to narrow down the problem scope and make sure there's actually a bug:
Can you connect Windows on the machine you're using directly to the SP site's WebDAV? google.com/search
Is the URL you've passed as a parameter to the client context constructor the same URL you'd use to connect to the WebDAV through Windows on that client machine?
hi,
can COM loads 2007 sharepoint sites??? im getting error. "The remote server returned an error: (500) Internal Server Error".?
Hi,
I have problem too (The remote server returned an error: (409) Conflict.)
I try to create item with attach in a custom list in SharePoint 2010 from a simple Windows Form
Im working in localmachine and i am Administrator in the server and in the SharePoint
Can u helpme?
Thanks
//using IO= System.IO;
public string NewItemAdjunto(string _nombreLista, string _url, string _titulo, string _detalles, string _pathArchivo)
{
try
using (ClientContext ctx = new ClientContext(_url))
Uri url = new Uri(_url);
Web site = ctx.Web;
ctx.Load(site);
ctx.Load(site.Lists);
string itemId = "13";
List lista = ctx.Web.Lists.GetByTitle(_nombreLista);
ListItemCreationInformation newInfo = new ListItemCreationInformation();
ListItem item = lista.AddItem(newInfo);
// Agregamos Valores
item["Title"] = _titulo;
item["Descripci_x00f3_n"] = _detalles;
item["Fecha"] = new DateTime(2010, 11, 10, 8, 0, 0);// Fecha en Duro
item.Update();
using (IO.FileStream strm = new IO.FileInfo(@"C:\Test\Adjunto1.txt").Open(IO.FileMode.Open))
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, "/Lists/Contenido%201/Attachments/" + itemId + "/" + "Adjunto1.txt", strm, true);
return "Item Creado con Adjunto";
catch
throw;
Hi All,
I am getting the error -The remote server returned an error: (404) Not Found.
While adding the attachment to the list Item using
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, attachmentPath, stream, true);
In my case i have created an event receiver feature already running on this list, which will add an attachment to the list item and will delete the same when the item is added.
I hope this will create the attachment folder for this list item, but still while adding attachments i'am getting the above file not found exception.
Please anybody guide me on this .
Thanks in Advance,
Dhileep.
Plz post code for list item with attachment. here only document library
If I use Microsoft.SharePoint.Client.File.SaveBinaryDirect I get error:
Microsoft.SharePoint.Client.ClientRequestException was unhandled
Message=Cannot invoke HTTP DAV request. There is a pending query.
Source=Microsoft.SharePoint.Client
StackTrace:
at Microsoft.SharePoint.Client.File.SaveBinary(ClientContext context, String serverRelativeUrl, Stream stream, String etag, Boolean overwriteIfExists, SaveBinaryCheckMode checkMode)
at Microsoft.SharePoint.Client.File.SaveBinaryDirect(ClientContext context, String serverRelativeUrl, Stream stream, Boolean overwriteIfExists)
at DisplayWebTitle.Main() in C:\Users\hehakama\Documents\Visual Studio 2010\Projects\ConsoleApplicationHH_GetFile\ConsoleApplicationHH_GetFile\Program.cs:line 69
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Is this because of some protocols are unavailable in our company's intranet?
I found the first method did not work for me until I added a
context.Load(docs);
between lines 10 and 11.
Sven/Sridhara
Did you guys found any solution for exception ("The underlying connection was closed: A connection that was expected to maintain their closed down the server"), if so can you please post it here.
Hi I can not upload a file more than 3 mb. can u tell me how to upload large files is thr any way??
I want to use client object model no server side code I want.
Bijay
http://www.fewlines4biju.com