Search code examples
c#.netgoogle-docsgoogle-docs-api

Updating a document in Google Docs using the API?


I want to update the contents of the already uploaded Google Doc file. I'm using the below code:

DocumentsService service = new DocumentsService("app-v1");
string auth = gLogin2();
service.SetAuthenticationToken(auth);
Stream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(
   "CONTENTS PLEASE CHANGE"));
DocumentEntry entry = service.Update(new Uri("feedURL"), stream, "text/plain", 
    "nameOfDoc") as DocumentEntry;

For "feedURL" I tried using all the possible links: alternate, self, edit, edit-media even resumable-edit-media, but I keep on getting exceptions.

Also how do I read a response with such requests?

I just started using this API. Earlier, I was using it on the protocol level so was sending GET/POST requests and receiving web responses. I don't know how to get or read response in this case.

UPDATE:

Now the code I'm using is:

RequestSettings _settings;
            string DocumentContentType = "text/html";
            _settings = new RequestSettings("Stickies", "EMAIL", "PASSWORD");
            var request = new DocumentsRequest(_settings);


            //var entryToUpdate = doc.DocumentEntry;
            var updatedContent = "new content..."; ;

            var mediaUri = new Uri(string.Format(DocumentsListQuery.mediaUriTemplate, rid));
            Trace.WriteLine(mediaUri);
            var textStream = new MemoryStream(Encoding.UTF8.GetBytes(updatedContent));

            var reqFactory = (GDataRequestFactory)request.Service.RequestFactory;
            reqFactory.CustomHeaders.Add(string.Format("{0}: {1}", GDataRequestFactory.IfMatch, et));
            var oldEtag = et;
            DocumentEntry entry = request.Service.Update(mediaUri, textStream, DocumentContentType, title) as DocumentEntry;
            Debug.WriteLine(string.Format("ETag changed while saving {0}: {1} -> {2}", title, oldEtag,et));
            Trace.WriteLine("reached");

And the exception I'm getting is: {"The remote server returned an error: (412) Precondition Failed."} I'm getting this exception at DocumentEntry entry = request.Service.Update(mediaUri, textStream, DocumentContentType, title) as DocumentEntry;


Solution

  • Solved.. Exception precondition Failed was due to Etag mismatch The above UPDATED code works perfectly for saving a document.