The .NET API for Google Docs is a strange beast. First, it has a DocumentsRequest class and a DocumentsService class. Sometimes you’ll need to use one class, sometimes the other and it’s not clear what the distinction is between the two. And I’d assumed the .NET API supported everything you could do with the raw HTTP API and hence I thought uploading a file or folder to a specific folder wasn’t possible. This led to further confusion when I tried to move a folder and it did move but left the original folder behind and I couldn’t figure out how to delete that folder. And as with most things from Google, the documentation is somewhat lacking.
So I eventually figured out I’d have to do a little work myself and came up with a couple of extension methods, one to create a folder and one to upload a file, but both accepting a parent folder. When I say I needed to do a little work, what I really mean is I used Reflector to see how the current methods worked and employed some copy and paste…
public static class GoogleDocsExtensions { public static Document CreateFolder(this DocumentsRequest docsRequest, string folderName, Document parentFolder) { Document doc = new Document(); doc.Type = Google.Documents.Document.DocumentType.Folder; doc.Title = folderName; if (parentFolder == null) return docsRequest.Insert<Document>(new Uri(DocumentsListQuery.documentsBaseUri), doc); else { return docsRequest.Insert<Document>(new Uri(parentFolder.AtomEntry.Content.AbsoluteUri), doc); } } public static void UploadFile(this DocumentsService docsService, string file, Document folder) { FileInfo info = new FileInfo(file); using (FileStream input = info.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { Uri uri = new Uri(folder.AtomEntry.Content.AbsoluteUri); string str = info.Extension.ToUpper().Substring(1); string contentType = (string)DocumentsService.DocumentTypes[str]; docsService.Insert(uri, input, contentType, info.Name); } } }
5 comments:
Thanks, I needed that.
OMG.... this is wht i want ...grt..
Thanks. It helped a lot
1 more question. How to update a collection(folder) name
This don't work for e.g. JPG files!
You know how to turn around this?
Been a long time since I've done anything with Google Docs so I can't help you, sorry!
Post a Comment