An updated version of this tutorial for Google Drive API V3 can be found How to upload a file to Google Drive with C# .net (Updated 2021). I recommend switching to Google Drive API v3 and not using this tutorial.
Have you been trying to connect your website or application to Google Drive? Would you like to see a list of files or a list of Directories stored on Google Drive? Would you like to Upload a file to Google Drive or download a file from Google drive using C# .Net using Visual Studio. In this tutorial series, we will be looking into the Google Drive API, using the Google .net Client library which makes accessing Google APIs much simpler. There are a lot of things you can do with the Google Drive API, List files and folders, Download files, Upload files, Change Files, Copy files, Delete Files, Trash Files, Create directory’s, delete directory’s. There is even a version of %appdata% on Google Drive where you can store your application specific files for each user.
[wp_ad_camp_3]
Five part Tutorial Series
- Google Drive API with C# .net – Authentication
- Google Drive API with C# .net – Files – Files, directories, search
- Google Drive API with C# .net – Upload, update, patch, delete, trash
- Google Drive API with C# .net – Download
- Google Drive API with C# .net – File Permissions
- Google Drive API with C# .net – Sample project
Restringing your application.
Like with most of the Google APIs you need to be authenticated in order to connect to them. To do that you must first register your application on Google Developer console. Under APIs be sure to enable the Google Drive API and Google Drive SDK, as always don’t forget to add a product name and email address on the consent screen form.
Project Setup
Make sure your project is at least set to .net 4.0.
Add the following NuGet Package
PM> Install-Package Google.Apis.Drive.v2
You will probably need most of these using’s
using System; using Google.Apis.Drive.v2; using Google.Apis.Auth.OAuth2; using System.Threading; using Google.Apis.Util.Store; using Google.Apis.Services; using Google.Apis.Drive.v2.Data; using System.Collections.Generic;
Authentication
This tutorial assumes that you have already read the tutorial about Google Drive API with C# .net – Authentication. I will not be going into how to create a valid Drive service if you haven’t created one already please go read that tutorial then come back here.
Now we have a drive service that we can preform perform though.
Upload
Directory
Remember directory’s are nothing but files with a different mime type. The following method will create a new allow you to create a new directory. Send parent = root if you would like it at the top directory. Other wise it must be a valid directory file resource id, you can get this using list with search to find the directory you are looking for.
//// /// Create a new Directory. /// Documentation: https://developers.google.com/drive/v2/reference/files/insert /// ///a Valid authenticated DriveService ///The title of the file. Used to identify file or folder name. ///A short description of the file. ///Collection of parent folders which contain this file. /// Setting this field will put the file in all of the provided folders. root folder. /// public static File createDirectory(DriveService _service, string _title, string _description, string _parent) { File NewDirectory = null; // Create metaData for a new Directory File body = new File(); body.Title = _title; body.Description = _description; body.MimeType = "application/vnd.google-apps.folder"; body.Parents = new List() { new ParentReference() { Id = _parent } }; try { FilesResource.InsertRequest request = _service.Files.Insert(body); NewDirectory = request.Execute(); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } return NewDirectory; }
Files
Remember from creating a directory in order to upload a file you have to be able to tell Google what its mime-type is. I have a little method here that try’s to figure that out. Just send it the file name. Note: When uploading a file to Google Drive if the name of the file is the same name as a file that is already there. Google Drive just uploads it anyway, the file that was there is not updated you just end up with two files with the same name. It only checks based on the fileId not based upon the file name. If you want to Update a file you need to use the Update command we will check that later.
// tries to figure out the mime type of the file. private static string GetMimeType(string fileName) { string mimeType = "application/unknown"; string ext = System.IO.Path.GetExtension(fileName).ToLower(); Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); if (regKey != null && regKey.GetValue("Content Type") != null) mimeType = regKey.GetValue("Content Type").ToString(); return mimeType; }
With that we can continue.
/// /// Uploads a file /// Documentation: https://developers.google.com/drive/v2/reference/files/insert /// ///a Valid authenticated DriveService ///path to the file to upload ///Collection of parent folders which contain this file. /// Setting this field will put the file in all of the provided folders. root folder. /// If upload succeeded returns the File resource of the uploaded file /// If the upload fails returns null public static File uploadFile(DriveService _service, string _uploadFile, string _parent) { if (System.IO.File.Exists(_uploadFile)) { File body = new File(); body.Title = System.IO.Path.GetFileName(_uploadFile); body.Description = "File uploaded by Diamto Drive Sample"; body.MimeType = GetMimeType(_uploadFile); body.Parents = new List() { new ParentReference() { Id = _parent } }; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile)); request.Upload(); return request.ResponseBody; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return null; } } else { Console.WriteLine("File does not exist: " + _uploadFile); return null; } }
Just like with creating a directory we need to supply our meta data information. We are using the GetMimeType method to find out the files mimetype. Then we are loading the File into a MemoryStream that we can use to send to service.Files.Insert. Once the file is done uploading you can get the request.ResponseBody and check for any errors. If a file.id is returned you know your file has now been uploaded.
Update
[wp_ad_camp_1]Google Drive is a little strange in my opinion. If you take the same fine and upload it again, you end up with two files. Personally i would rather see the first one over written, but thats not how Google has chosen to do things. So that is where update comes in. If you want to make a change to a file then you will need to update the file. To update a file in Google drive you will need the file resource id of the file you would like to update.
/// /// Updates a file /// Documentation: https://developers.google.com/drive/v2/reference/files/update /// ///a Valid authenticated DriveService ///path to the file to upload ///Collection of parent folders which contain this file. /// Setting this field will put the file in all of the provided folders. root folder. ///the resource id for the file we would like to update /// If upload succeeded returns the File resource of the uploaded file /// If the upload fails returns null public static File updateFile(DriveService _service, string _uploadFile, string _parent,string _fileId) { if (System.IO.File.Exists(_uploadFile)) { File body = new File(); body.Title = System.IO.Path.GetFileName(_uploadFile); body.Description = "File updated by Diamto Drive Sample"; body.MimeType = GetMimeType(_uploadFile); body.Parents = new List() { new ParentReference() { Id = _parent } }; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.UpdateMediaUpload request = _service.Files.Update(body, _fileId, stream, GetMimeType(_uploadFile)); request.Upload(); return request.ResponseBody; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); return null; } } else { Console.WriteLine("File does not exist: " + _uploadFile); return null; } }
Notice how this time we use service.files.update() and we get an FileRecources.UpdateMediaUpload back. You probably don’t want to to loop though all of the files updating them all. It would probably make more sense to figure out exactly which file it is.
Patch
There is a second way to Update a file. If all you want to do is change its meta data then you can use Patch.
File file = new File(); file.Title = newTitle; // Rename the file. FilesResource.PatchRequest request = service.Files.Patch(file, fileId); File updatedFile = request.Fetch();
This will simply rename the file with out changing the continence of file itself.
Delete
Finally we come to delete. Delete like Update and upload requires the fileId. Use the same code as we used above only instead of all the Metadata and stream stuff just use this
FilesResource.DeleteRequest DeleteRequest = service.Files.Delete(file.Id); DeleteRequest.Execute();
This will permanently delete the file with that id. It skips the trash.
Trash
Instead of permanently deleting a file you can simply trash it.
service.files().trash(fileId).execute();
You can also untrash a file
service.Files.Untrash(fileId).Fetch();
Trashing is probably better then deleting unless you ask the user if they are sure they want to delete the file.
Concision
You should now understand how to access the Google Drive API with an authenticated user. You should also understand how to upload files to Google Drive, how to update a file on Google Drive. We have also talked about the difference between deleting and trashing files from Google Drive. I hope you will also agree that working with the Google APIs is quite easy once you get the authentication down.
This is good stuff. It is nice to find all this information in one place. And it is very concisely written.
You should have someone proof read it though. The typo-s detract from your expert instruction.
Unfortunately hiring someone to proof read the site is not an option, I don’t charge for any of this so you are stuck with what i can do on my own. Feel free to email me typo’s I normally put it though Google doc’s spell checker, which apparently isn’t enough.
hi linda. i was create succes file excel on google driver. but i only get file ID in google driver. how to get ID file excel like:
https://docs.google.com/spreadsheets/d/1oLX6FV3aFJNIjaad3Bj0BDH1q6TPRL8V73Bf3k-7Zrk/edit#gid=0
“1oLX6FV3aFJNIjaad3Bj0BDH1q6TPRL8V73Bf3k-7Zrk” this key, i want get it. Thanks you so much.
When you create a file you should get a file.resource back. check selfLink and alternateLink see if one of those is what you are looking for.
Your site is really helpful thanks for your work ! I have 2/3 questions:
-do you have any sample to show how to change permission on an uploaded file ?
– when you upload a file with a service account how can you find your file with the standard drive web interface ?
I cannot understand with the service account which user space they are consuming
Thanks
Alberto
A service account is its own sudo user, it has a google drive account, a google calendar account … probably a bunch more. Any files uploaded to the service account cant be seen though the web intervace unless you give say yourself or someone else access to the file. I havent added that to the sample project but i can put it on my list.
I found this in the documentation though: Permissions:patch
///
///
/// Drive API service instance.The patched permission, null is returned if an API error occurred
/// ID of the file to update permission for.
/// ID of the permission to patch.
/// The value "owner", "writer" or "reader".
///
public static Permission PatchPermission(DriveService service, String fileId,
String permissionId, String newRole) {
Permission patchedPermission = new Permission();
patchedPermission.Role = newRole;
try {
return service.Permissions.Patch(patchedPermission, fileId, permissionId).Execute();
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
}
return null;
}
Does this mean I can login in google with the service account on the web and see calendar / drive and other stuff ? thanks for your help
Your code is very helpful. I have tried to work out how to edit an existing spreadsheet. All I can find is for gdata and I believe that it no longer works. I want to add data from another source to the sheet. Any pointer or help would be appreciated.
Your article is very nice. It helps me to do almost all operation but I am not able to delete file from the drive.
Issue:
Few files were previously uploaded so their owner is xyz@domain.com. Now we have created service account using this domain account but we are not able to delete those files as owner is different.
Any solution ??
Thanks in advance.
The owner of the file will either have to delete them himself / herself or grant the service account access to delete the files. No one can delete files owned by someone else not even a mighty service account 🙂 Congrats on getting this far.
Thanks for your reply.
How to grant the service account access to delete the files ? Who can do it ?
Thanks
You need to go to Google drive and add the service account to the file with full access if you want it to be able to delete a file.
What do you mean by full access ? I can give “Can Edit” access to service account but it does not allow me to delete the file. And I am not able to make service account “Is Owner” because it gives me error like “Ownership can not be transferred in different domain.”
I got the error but I want to know is there any way to transfer ownership from xyz@domain.com to service account email id (random generated by key) ?
I am actually not sure this is even possible. I have seen a number of people trying but i don’t have access to a domain account to test with. try asking on stackoverflow.com maybe someone there knows.
I did enjoy reading your tutorials. I was about to create an application that needed a huge amount of storage, so I chose Google Drive, and I was somehow stuck in how to programmatically manage it. Your articles was of great help. Thank you.
Hi, I use the upload method, but receive request.ResponseBody = null and the following exception ‘Value cannot be null.Parameter name: baseUri’, what can be the problem?
Hi again – I tried to edit my question but didn’t succeed :-), I saw now the same question at http://stackoverflow.com/questions/30172836/uploading-with-google-drive-sdk
Thanks a lot for your blog – it helps me a lot
NP: comments have to be approved first they I have been getting to much spam lately.
I thought there is an answer on stackoverflow – but there isn’t ….
Is there an answer for that question?
request.ResponseBody; only returns if your file was uploaded successfully. You need to figure out why your file wasn’t uploaded. start with a easy empty text file or something debug your way up.
The base uri That I see in the service is “https://www.googleapis.com/drive/v2/” and this is the answer I receive from Google after I send RefreshToken, ClientId and ClientSecret.
I tried to browse and got Not Found – what do I need to get a valid url?
Ok…. I found the problem – After updating via nuget Zlib.Portable is updated to version 1.110.0, while Google is using version 1.10.00 — that was frustrating and I’m glad I manage to find what was the problem – Thanks for your patient and for answers
The Zlib.Portable update will be part of the new version of the client library we hope to release next week.
Thanks for the info, will do updating
Your articles have been a great help in enabling me to understand working with the Google Drive API. Using them I have managed to write a small program that can authenticate, down load a list of files and also using one of the file IDs download the file to my hard drive. However I cannot get a file to upload. Using the code above I get the same error as Ishay – Value cannot be null. I am also using the ZLib.portable version 1.110.0. Sorry but I do not understand how to get past this problem. Can you please offer some help?
I have seen a few people with this issue, but I have not been able to recreate the problem myself.
i love you
Hi there,
i really like the example. But after upload i want to share the link to the file=
?
How to do these? Many thanks
file.insert returns a file response i would assume there is a link in there for the file. I will see if i can create an example post for this.
It was a very good question here you go. Drive API Link to file
can you provide sample code cos i am new to mvc and is there any solution to upload files in sites admin’s single account using mvc or some links that will help me to achieve this???
unfortunately I don’t have access to a sites admin account so I haven’t been able to create any tutorials for that.
hi.. i create project using google drive.
i can’t upload any file on google drive as this stuff.
ClientSecrets secrets = new ClientSecrets()
{
ClientId = parameters.ClientId,
ClientSecret = parameters.ClientSecret
};
var token = new TokenResponse { RefreshToken = parameters.RefreshToken };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets
}),
“xxxx@gmail.com”,
token);
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = “Google Drive”,
});
if (FileUpload1.HasFile)
{
var filename = FileUpload1.FileName;
var filepath = FileUpload1.PostedFile.FileName;
Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
body.Title = filename;
body.Description = “Documents”;
body.MimeType =GetMimeType(filename);
body.Parents = new List() { new ParentReference() { Id =”root” } };
//byte[] array = System.IO.File.ReadAllBytes(filepath);
System.IO.MemoryStream stream = new System.IO.MemoryStream(FileUpload1.FileBytes);
FilesResource.InsertMediaUpload fileuploadrequest = new FilesResource.InsertMediaUpload(service, body, stream, GetMimeType(filename));
var name=MediaFileSource.GetContentTypeForFileName(filename);
fileuploadrequest.Convert = true;
fileuploadrequest.Upload();
Google.Apis.Drive.v2.Data.File response = fileuploadrequest.ResponseBody;
response is null…
please give me asolution for this
thanks…
I think you should post your question on stackoverflow.com you don’t appear to be following my tutorial. you could also just try my tutorial.
How to automatically convert to docs ?
file.insert has an alternate parameter called convert which will convert the file uploaded to doc format.
Hi Linda
Thanks for great tutorials. These have helped me to get started and have a better understanding of the api.
I have a doubt and I hope you could help in figuring out. Here is my problem description:
I am using google drive v3 api to upload a file and then preview it in browser using web view link in the response. But web view link is coming null. When i was using v2, I was able to do it using alternate link.
I have not set the parent ref so I am assuming as per the documentation, the file is stored in my drive folder(root) of service account. As I couldn’t login to service account, so I shared the file with my existing test gmail account and it was shared.
My question is how can I open the file in browser using System.Diagnostics.Process.Start(newFile.WebViewLink);
here is my code:
{
File fileInGoogleDrive = Utils.uploadToDrive(service, pathOfTheFileToBeUploaded, “root”); // code of this method below
Permission toShare = new Permission();
toShare.EmailAddress = “xyz@gmail.com”;
toShare.Type = “user”;
toShare.Role = “reader”;
PermissionsResource.CreateRequest createRequest = service.Permissions.Create(toShare, fileInGoogleDrive.Id);
createRequest.Execute();
return fileInGoogleDrive.WebViewLink; //THIS IS NULL
}
// Upload to drive code
public static File uploadToDrive(DriveService _service, string _uploadFile, string _parent = “root”)
{
if (!String.IsNullOrEmpty(_uploadFile))
{
File fileMetadata = new File();
fileMetadata.Name = System.IO.Path.GetFileName(_uploadFile);
fileMetadata.MimeType = GetMimeType(_uploadFile);
//fileMetadata.Parents = new List() { new FilesResource() {}};
try
{
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.CreateMediaUpload request = _service.Files.Create(fileMetadata, stream, GetMimeType(_uploadFile));
request.Upload();
return request.ResponseBody;
}
catch (System.IO.IOException iox)
{
// Log
return null;
}
catch (Exception e) // any special google drive exceptions??
{
//Log
return null;
}
}
else
{
//Log file does not exist
return null;
}
}
I will be really grateful if you guide me on this.
Thanks in advance 🙂
Hi Lynda
WRT my previous comment, I figured out the syntax of getting fields from v3 api to get webViewLink. Wanted to know the second part of how I can view it in browser. As this is the service account, the link generated tells needs permission. So when I add permission for another user, I can see the file inside the drive after logging in. How can I get that share url or how can the service account delegate control such that the file opens up in browser after getting data from drive api?
Web Search shows me using domain wide delegation and adding permissions for another user. i tried the permissions one and as told above, I wanted to pop the file in browser after getting results and not check in that user’s drive.
Sorry about the long post but I am confused with the logic here.
I really haven’t had time to look to much into the new API. Its on my list and i have a sample project built for it but that’s as far as i have gotten.
I have a question.
How to make the file upload is public to everyone?
My file is private. 🙁
You need to insert permissions on the file to make it public Permissions: insert
How do I check if the file is in the trash ?
thanks, from Brazil 🙂
how do I know if the folder is in the trash ?
The File resource has a field called trashed in V2 as does V3
yeah! File.Labels.Trashed *o* thanks.
Hi. I´m able to do it with net framework 4, can this work on net framework 3.5?
Thanks
No the Google Apis .net client library only supports .net framework 4.0 and 4.5. They are in the process of removing 4.0 support I suggest you switch to 4.5
Hi DalmTo,
I had read through your article, I want to upload a file, when i copy your code in my console application. body.Parents = new List() { new ParentReference() { Id = _parent } }; the List() will get has the error, may i know how to solve it.
what is the error?
This one:
CS1922 Cannot initialize type ‘List’ with a collection initializer because it does not implement ‘System.Collections.IEnumerable’
This one:
CS1922 Cannot initialize type ‘List’ with a collection initializer because it does not implement ‘System.Collections.IEnumerable’
In order to work, changed it to:
body.Parents = new List() { new ParentReference() { Id = _parent } };
This one:
CS1922 Cannot initialize type ‘List’ with a collection initializer because it does not implement ‘System.Collections.IEnumerable’
In order to work, changed it to:
body.Parents = new List() { new ParentReference() { Id = _parent } };
(You may delete the previous posts, made a mess)
Hi Linda, great samples !
I have created a method based on your sample ‘updateFile’ . I use google drive v3. my methods runs without any error, but the content of the targetfile does not change. uploading an deleting files on my drive-account works fine.
Do you have any idea why the method failed?
In v3 there are two functions for updating files. first creates a UpdateRequest to patch metadata and second creates a UpdateMediaUpload to update content. my method uses the second one.
unfortunately all i have done is generate some sample code for v3 i haven’t tried to use it yet. I will find sometime this week to take a look. Google hasn’t uploaded any tutorials for it yet i think its time i do.
i resolved it by myself (and with forum: After update to API v3 Update won’t work Link => https://github.com/google/google-api-dotnet-client/issues/668).
The error results because of using non writeable fields for File-Parameter. I took the File-Instance from a previous Get() -Call.
If i create an empty File-Parameter and set only the Name-attribute, the function works. The last question is: Which attributes are writeable? But this has to be specified by google.
thanks
Hello there Maam Linda. I reading your article and very interested on your tutorial. Right know, i followed your tutorial but unlucky I was unable to upload file. Could you give a sample project that I could just change the client id and client key? So that I could try uploading files in my google drive. I am really new in c#, I am just using it 2 weeks right now. Hope you helps me. Thanks and advance
There is a project on GitHub with a helper class that might help you. DaimtoGoogleDriveHelper.cs
Hello there!
Thank you for the help
I already understand how it works.
Could I ask I am trying to save all images in a folder. when i try root/Image which is the image is my folder it doesn’t upload file. Could you help me with this problem
Files.insert
// Set the parent folder.()
if (!String.IsNullOrEmpty(parentId)) {
body.Parents = new List
{new ParentReference() {Id = parentId}};
}
You need to get the id of the image folder. Try using files.list to find it.
Getting the ID of the folder do the trick.
Thank you for the great tutorial
Getting the ID of the folder do the trick.
I can now upload image in my folder.
Thank you for the great tutorial.
Hello there!
Thank you for the help
I already understand how it works.
Could I ask I am trying to save all images in a folder. when i try root/Image which is the image is my folder it doesn’t upload file. Could you help me with this problem
Dear Linda,
Its really a helpful article but i have one query.
I have created a folder in google drive directly from web. Now i want to create file in that folder. You have said that i need directory file resource id of that folder in order to create file in that folder. I know a name of that folder but i dont know how to get its Id. Can you please guide me. Code snippet will be helpful.
Regards,
Hassaan Kamran
Thanks. It works great. But when i try to upload bigger files (like 100 MB) , Visual Studio throws TaskCancelledException with additional information : “A task was cancelled.” and the upload is aborted half way. Why does this happen? And how do I fix it? Thanks.
I think you should create an example of your code and put it up on Stackoverflow.com with your problem. I will either spot it or someone else will.
Is there a page like this for v3? This page has several syntax errors in Upload File when using v3.
– GetMimeType
– InsertMediaUpload
– ParentReference
– Files.Insert
Net yet I am working on getting a v3 sample project together. Then putting some tutorials up for it. Google hasn’t made any documentation for it for C# yet I guess I need to do that for us.
I need to check free space i got the code but not, working
About about = service.About.Get().Execute();
about.QuotaBytesTotal=”Total bytes is coming”
about.QuotaBytesUsed=”0″ is coming
How to slove this
sounds like the account you are authenticating with doesn’t have anything on its drive account. Would this by any chance be a service account?
Hello
I need a little explanation about _parent.
How I can put file into sub folder.
Thank yiuy
Normally i do a File.list to find the file id of the sub folder i want to upload my file to. Remember directories are also files in google drive. Then when you upload the file you set the parent to the Id of the sub folder you found in your file.list.
It does actually make sense when you think about it a little.
I am using the below code to upload an image file to Google Drive using Selenium C#. But I am getting null value for request.ResponseBody.
Please let me know the solution for this:
Code –
using Google.Apis.Drive.v3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Util;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using System.Collections.Generic;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
public void AuthenticateServiceAccountJSON()
{
string keyFilePath = @”C:\RateCrawlingProject\RateCrawlingProject-1bdd62b6b3db.json”;
// check the file exists
if (!System.IO.File.Exists(keyFilePath))
{
Console.WriteLine(“An Error occurred – Key file does not exist”);
}
else
{
string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents
DriveService.Scope.DriveAppdata, // view and manage its own configuration data
DriveService.Scope.DriveFile, // view and manage files created by this app
DriveService.Scope.DriveMetadataReadonly, // view metadata for files
DriveService.Scope.DriveReadonly, // view files and documents on your drive
DriveService.Scope.DriveScripts }; // modify your app scripts
Google.Apis.Drive.v3.DriveService service;
using (var stream = new System.IO.FileStream(keyFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
var credential = GoogleCredential.FromStream(stream);
if (credential.IsCreateScopedRequired)
{
credential.CreateScoped(scopes);
}
// Create the service.
service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = “MyDrive”,
});
}
string filepath = @”C:\RateCrawlingProject\RateCrawlingProject\hc1.jpg”;
if (System.IO.File.Exists(filepath.ToString()))
{
File body = new File();
body.Name = System.IO.Path.GetFileName(filepath.ToString());
body.Description = “Test Description”;
body.MimeType = “image/jpeg”;
byte[] byteArray = System.IO.File.ReadAllBytes(filepath);
System.IO.File.Delete(filepath);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.CreateMediaUpload request = service.Files.Create(body, stream, “image/jpeg”);
request.Upload();
File file = request.ResponseBody; //returns null value
}
}
}
I just tested it with your code it ran fine. Not sure what your problem could be other then maybe your file does not exist?
string filepath = @”C:\Users\linda_l\Documents\deleteme.txt”;
if (System.IO.File.Exists(filepath.ToString()))
{
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
body.Name = System.IO.Path.GetFileName(filepath.ToString());
body.Description = “Test Description”;
body.MimeType = “text/plain”;
byte[] byteArray = System.IO.File.ReadAllBytes(filepath);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.CreateMediaUpload request = service.Files.Create(body, stream, “text/plain”);
request.Upload();
Google.Apis.Drive.v3.Data.File file = request.ResponseBody; //returns null value
}
it’s not direct to google drive and it returns null
I suggest that you take your code and ask a question over on http://stackoverflow.com/
Include your code and any error messages you are getting so that everyone can test it.
Looking forward to your dotnet core versions of these 🙂
Thanks for your very helpful coverage of the Google Drive API for .NET. I’ve been using the v2 API (based on your samples) for a few years now. I thought I had the Trash method working, but it no longer seems to trash. And in experimenting with v3, which doesn’t seem to have a Trash method, I am making calls to Files.Delete(fileId), but the delete doesn’t occur. No error, just no delete. Do you know how to achieve a delete in the .NET API (v3 or if not possible, v2)? Thanks!
try Files: update it has an option
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
I get an error saying missing assembly reference…. unidentified type !! (kindly mail me, i have got a lot things to learn from you)
Try the documentation the code may be more up to date Uploading Files click the .net tab
How to view the documents uploaded to the service acccount ?
Your going to either have to download it. Or grant your personal Gmail account permissions to see the file using Permissions.create
Thank You Very Much !
google apis are not working with .net 4.0
exception System.net.http version 1.5 not found,
.net framework having version 2.2.29.0
The Google .net client library no longer official supports .Net framework 4.0 you need to go to use a min of .Net 4.5 i think. If you grab the Nuget Package something prior to 1.11 it should work with 4.0
is there a version of this tutorial for Google.Apis.Drive.v3? i have tried this one with v2 (and v3 after making some necessary adjustments) and I cant get it to work, the File object returned is always null and the file never uploads.
Thank you
No i haven’t gotten around to writing any tutorials for drive v3 yet the team has created one though download files Let me know if you have any problems with it and I will give it a go myself.
Hello Linda.
I have problem from very beginning.
When I use Your code (it’s vb.net) :
`Dim upl As FilesResource.InsertMediaUpload = service.Files.Insert(TheFile, IO.File.OpenRead(zipFilePath), TheFile.MimeType)`
I got error : “Too many arguments to ‘Public Overridable Function Insert(body As Google.Apis.Drive.v2.Data.File) As Google.Apis.Drive.v2.FilesResource.InsertRequest’.”
I just, can’t use service on this way at all.
All required namespaces are imported.
service.File.Insert just won’t be override.
Thanks for help.
Sorry i haven’t worked with VB.net in 12 years I am not going to be much help trying asking on stackoverflow.com
Hello Linda:
The file I am trying to upload is having large size, So I am trying to upload file chunks asynchronously. But its not working.
Here is my psudo code
///Authentication and creating Drive service
{
……
…….
}
String _FileID = null;
///Creating file initially and assigning properties
{
File _GoogleFile = new File();
_GoogleFile.title = “File 1”;
_GoogleFile.Parents.Add(ParentReference);
_GoogleFile = DriveService.Files.Insert(_GoogleFile).Execute();
_FileID = _GoogleFile.Id;
}
/// Reading source file chunk by chunk and uploading the data
{
File _GoogleFile = new File();
_GoogleFile = DriveService.Files.Get(_FileID).Execute();
FilesResource.UpdateMediaUpload _UpdateMedia = DriveService.Files.Update(_GoogleFile, _FileID,dataStream, _GoogleFile.MimeType);
_UpdateMedia.Upload(); /// This is working.
// But If I use UploadAsync() not getting any response/error.
}
Thanks in Advance
Mayuresh
try playing with this. Upload Media
how can I use it on Visual Studio 2012?
thanks!
It should work as long as you have the project set to .net 4.5+
i got error when upload
ResumableUpload.cs
at Google.Apis.Upload.ResumableUpload`1.Upload() in C:\Users\mdril\Documents\GitHub\google-api-dotnet-client\Src\GoogleApis\Apis\[Media]\Upload\ResumableUpload.cs:line 353
error occur because request time out
equest.Service.HttpClient.Timeout = TimeSpan.FromMinutes(30);
and its done,
Is it necessary to create directory and files to upload files to Google Drive. Please clarify my doubt.
I am not sure i understand your question. Yes a file needs to be created before it can be uploaded.
no, its not require to create directory in drive,
you can also upload to drive root directory,
Prince please tell us how you share a users root directory with a service account. I have not been able to do this.
Hi linda ,
I am usng following code , Its working fine but their is one basic problem it send Request URI with random ports.
public string GoodgleImport()
{
ClientSecrets obj = new ClientSecrets();
UserCredential credential;
obj.ClientId = System.Configuration.ConfigurationManager.AppSettings[“Google.Client.ID”];
obj.ClientSecret = System.Configuration.ConfigurationManager.AppSettings[“Google.Client.Secret”];
FileDataStore ds = new FileDataStore(GoogleWebAuthorizationBroker.Folder);
ds.DeleteAsync(“user”).Wait();
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
obj,
Scopes,
“user”,
CancellationToken.None, null).Result;
var driveService = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = “My Report”,
MimeType = “application/vnd.google-apps.spreadsheet”
};
FilesResource.CreateMediaUpload request;
using (Stream s = GenerateStreamFromString(ConvertTableToString(GetTable()).ToString()))
{
request = driveService.Files.Create(
fileMetadata, s, “text/csv”);
request.Fields = “id”;
request.Upload();
}
var file = request.ResponseBody;
ds.DeleteAsync(“user”).Wait();
}
You need to set up visual studio so that it doesnt use random ports.
Hi Linda,
I am trying to upload the files to google drive. I have an service account with domain wide authority enabled. But within our domain, I was not able to share this service account with the google drive folder. Is there any way to impersonate another user for service account?
Try asking this on stackoverflow.com i dont have access to a gsuite account so cant give any more information then what is already in Googles documentation.
Hi Linda,
I am Roy and here’s my question on a drive V3 API permissions.update just now posted on StackOverFlow.
https://stackoverflow.com/questions/48891303/google-drive-api-v3-c-sharp-permissions-update-exception-the-resource-body-incl
Was hoping if you can also take a look and suggest some remedy.
My code below using Google Drive API v3 to transfer ownership from one user to another in the same domain is throwing this exception. I am using Service Account with domain-wide permissions for authorization piece.
string FileID = “xxxxxxxxxxxxxxxxxxx”;
var getRequest1 = OwnerDrive.Files.Get(FileID);
getRequest1.Fields = “owners,name,parents,mimeType,permissions”;
var afile = getRequest1.Execute();
foreach (var perm in afile.Permissions)
{
Console.WriteLine(perm.EmailAddress + ” : ” +
perm.DisplayName + ” : ” + perm.Role + ” : ” + perm.Id);
}
// I manually note down the permissionID of the current owner as
“14016095883385444520”
//Set New owner
Permission p = new Permission();
p.Role = “owner”;
p.Type = “user”;
p.EmailAddress = “newowner@xyz.com”;
var updateRequest = OwnerDrive.Permissions.Update(p, FileID,
“14016095883385444520”);
updateRequest.TransferOwnership = true;
updateRequest.Execute();
The error\exception throw is this: “Message[The resource body includes fields which are not directly writable.] Location[ – ] Reason[fieldNotWritable] Domain[global]”. The new drive v3 API says to use Permissions.Update and pass it permissionID which I am doing (although manually). What am I missing here ? Any help is greatly appreciated.
You my friend appear to have hit bug. Check my answer on stack. Well spotted.
Ho Ho. Thanks and thanks for filing the bug report. I will keep an eye on it.
Although it looks like “Permissions.Create(p, FileID)” works for ownership transfers in V3.
Not sure what would be the use case for “Permissions.Update(p, FileID, pemrissionID)” then ?
Good question there isnt much documentation for v3 its just a matter of testing stuff i guess.
HI Linda,
I have another one. I am trying to use the Google “Data Transfer API” for the first time and want to do drive transfers from 1 user to another in the domain using a service account. The documentation (https://developers.google.com/admin-sdk/data-transfer/) says:
“Construct a transfer resource that specifies the source and destination users and the applications for which to transfer data”
Can you help me with an example on how to create this “transfer resource” in C# ?
I tried creating the “DataTransfer” body JSON using this string representation below
String str = “{\r\n \”oldOwnerUserId\”: \”oldowner@mydomain.com\”,\r\n \”newOwnerUserId\”: \”newOwner@mydomain.com\”,\r\n \”applicationDataTransfers\”: [\r\n {\r\n \”applicationId\”: \”55656082996\”\r\n }\r\n ]\r\n}”;
But how do I pass it to the “DataTransfer” body I am not sure. Can you please advise ?
Thanks,
Roy
Hi Linda, Thanks for your help.
I know that it says “Website” in your initial paragraph but, can you confirm if its possible to use C# and Google Drive V2 for an asp.net (or other) project to let the users upload files to a service account? Its necessary for me because I dont want to use the transfer montly quote when the users upload their files.
PS: I did before some VB.Net and C# desktop apps that upload files to a service account but I’m not sure if this could be useful to apply it in websites.
Regards.
Yes you can use service account to upload but the user is going to have to add the service account email address to what ever folder they want to upload to.
Thank you very much, best regards.
Hi Linda,
Sorry to bug you again.
I think I got around the problem of how to use the Google’s Drive Transfer API but I still get an exception. Here’s my question on SO:
https://stackoverflow.com/questions/49266652/drive-transfers-using-google-data-transfer-api-in-c-sharp
It would be great help if you can take a look and provide your inputs.
Thanks,
Roy
Can I upload a file without authentication? I have a link to a shared folder. and I want to upload a file to it.
No you will always need to be authenticated in order to upload a file
trying to upload a file to a google drive folder that I have the sharable link only:
I don’t want to authenticate just upload the file to that folder.
How can I do that using the DriveService?
you cant if you want to upload to a google drive account you need to be authenticated even if that folder is set to public.
body.Parents = new List() { new ParentReference() { Id = _parent } };
instead
body.Parents = new List() { new ParentReference() { Id = _parent } };
Greate tutorial …
Is there an example on using upload large file chunkedupload()?
Hello!
Does this work for csharp winform?
It should.
How could you declare a variable of File Type ? Its a static type 😐
Because the File = Google.Apis.Drive.v3.Data.File not System.IO.File
Hi, Can you please give me a reference to save files directly into shared drives.
Sharied drives as in gsuite? You need to add supportsAllDrives and the driveId when uploading i think.
Thanks Linda, I am able to save files in shared drive by setting SupportsAllDrives = true; to request. But when I am trying to move files from My Drive to Shared drive by using the following code I am getting some error. Is it possible to move files from My Drive to Shared Drive using Google Drive API. Manually I can move files between drives by logging into Google Drive directly.
Code:
Google.Apis.Drive.v3.FilesResource.UpdateRequest updateRequest = service.Files.Update(new Google.Apis.Drive.v3.Data.File(), fileId);
updateRequest.SupportsAllDrives = true;
updateRequest.Fields = “id, parents”;
updateRequest.AddParents = folderId;
updateRequest.RemoveParents = previousParents;
file = updateRequest.Execute();
Error:
Google.Apis.Requests.RequestError Moving folders into shared drives is not supported.
[403] Errors [ Message[Moving folders into shared drives is not supported.]
Location[ – ] Reason[teamDrivesFolderMoveInNotSupported] Domain[global] ]
as the message states thats not currently supported by the api they are working on it.
Getting following error when i try to delete a file
Google.GoogleApiException: ‘Google.Apis.Requests.RequestError
Insufficient Permission: Request had insufficient authentication scopes. [403] error
Check which scopes you have autorized your user as delete requires one of the following
Hello, Linda. Can you tell me please about sharing folder with the service account. If the service account would be full in a few years, can i use it still to upload to my shared folder on the main account? And if i upgrade my main account storage space, does it affects the service account space? And finally, shared folder owner must be service or main account? Thanks.
If you store the files on your main account the the storage should be taken from that. You just need to share a folder on your main account with the service account and it should have access to write to the folder. Just remember to add permissions on the file to your main account so that you can delete it yourself.