I'm making a simple Application that Links to a Google Drive Account and then can Upload Files to any Directory and respond with a (direct) download Link. I already got my User Credentials and DriveService objects, but I can't seem to find any good examples or Docs. on the APIv3.
As I'm not very familiar with OAuth
, I'm asking for a nice and clear explanation on how to Upload a File with byte[]
content now.
My Code for Linking the Application to a Google Drive Account: (Not sure if this works perfectly)
UserCredential credential;
string dir = Directory.GetCurrentDirectory();
string path = Path.Combine(dir, "credentials.json");
File.WriteAllBytes(path, Properties.Resources.GDJSON);
using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) {
string credPath = Path.Combine(dir, "privatecredentials.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Drive API service.
_service = new DriveService(new BaseClientService.Initializer() {
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
File.Delete(path);
My Code for Uploading so far: (Does not work obviously)
public void Upload(string name, byte[] content) {
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
body.Name = name;
body.Description = "My description";
body.MimeType = GetMimeType(name);
body.Parents = new List() { new ParentReference() { Id = _parent } };
System.IO.MemoryStream stream = new System.IO.MemoryStream(content);
try {
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
request.Upload();
return request.ResponseBody;
} catch(Exception) { }
}
Thanks!