How to upload to Google Drive API from memory with C# 4


Google drive api

Google drive API standard examples.

Most of if not all of the upload samples and examples for the Google drive api refer to it as file upload data. This implies that you have a file on your disk that you wish to upload. Even all of my own How to upload a file to Google Drive with C# .net. This then leads you to wonder what would happen if the data you wish to upload isn’t actually on your disk. What if its in memory?

What if the data isn’t in a file?

Lets consider this for a moment. What if your system generates invoices. You build up the invoice and its all stored within a variable within your application. Now you want to upload the invoice to Google drive for storage, this is probably a bad example as you would probably want to store them in the database.

Now if we look at all the upload samples for the Google drive api they are going to make you think that you will first need to save the file to disk before creating a file stream to upload it to Google drive. The fact of the matter is you dont have to. You can upload a memory stream as well.

var uploadString = "Test";
var fileName = "ploadFileString.txt";
// Upload file Metadata
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
    {
     Name = fileName,
     Parents = new List<string>() { "1R_QjyKyvET838G6loFSRu27C-3ASMJJa" }  // folder to upload the file to
     };

var fsSource = new MemoryStream(Encoding.UTF8.GetBytes(uploadString ?? ""));

string uploadedFileId;
            
// Create a new file, with metadata and stream.
var request = service.Files.Create(fileMetadata, fsSource, "text/plain");
request.Fields = "*";
var results = await request.UploadAsync(CancellationToken.None);

if (results.Status == UploadStatus.Failed)
   {
   Console.WriteLine($"Error uploading file: {results.Exception.Message}");
   }
// the file id of the new file we created
uploadedFileId = request.ResponseBody?.Id;

In the above code I have a string variable called uploadString this variable is storing some text that I wish to upload to google drive to a text file called fileName. The key part of this code is where I concert the uploadString to a memory stream. Normally we would create a File Steam if we are reading the file from disk.

Conclusion

You can use any type of stream to upload the file to Google drive api. Normally we think of uploading Files so we would use a file stream reading all the file data into the stream and then uploading it. However if is possible that the data may already reside within your application in memory in which case you can just upload the data as a memory stream.

I would like to take the time to thank user Richard on stack overflow for asking this question How to save a file to Google Drive from Flutter web without a local file on disk? The question was related to Flutter but I was intrigued as it was not something I tried before. Works like a charm.


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

4 thoughts on “How to upload to Google Drive API from memory with C#

  • champion

    hi,
    I try to follow your code but I lost. I code in c#. first thing is the Google Apis 1.57.0 this is no Google.Apis.Drive.v3.Data.File()
    so what is the correct one.
    well in fact is what is the correct code to upload a stream to a drive file?
    And where do we get the “1R_QjyKyvET838G6loFSRu27C-3ASMJJa” string for our files?

    Best regard

        • Linda Lawton Post author

          If you don’t add parents by default it will upload to the root folder of the currently authenticated user. If that user is a service account then it will upload to the service accounts root folder. If it is a normal user then it will upload to that users root folder.

          To upload from a service account to your personal drive account the folder must be shared with the service account. You can not share the root folder of your personal google drive account with anyone there for you must create a folder that it has access to.