How to download file from google drive in c#? - c#

I am trying to download file from Google Drive using ASPSnippets.GoogleAP.dll and Google.Apis.Drive.v3.dll. But facing some challenges. File is being downloaded, but it is in some type of weird HTML content.
I am using following code to download it :
GoogleConnect.ClientId = "xxxx.apps.googleusercontent.com";
GoogleConnect.ClientSecret = "xxxxxx";
GoogleConnect.RedirectUri = Request.Url.AbsoluteUri.Split('?')[0];
GoogleConnect.API = EnumAPI.Drive;
if (!string.IsNullOrEmpty(Request.QueryString["code"]))
{
string code = Request.QueryString["code"];
string json = GoogleConnect.Fetch("me", code);
GoogleDriveFiles files = new JavaScriptSerializer().Deserialize<GoogleDriveFiles>(json);
//Remove the deleted files.
var driveService = new DriveService();
Label1.Text = theHiddenField1.Value;
WebClient wb = new WebClient();
wb.DownloadFile(theHiddenField1.Value, "C://" + fileName);
}
else if (Request.QueryString["error"] == "access_denied")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Access denied.')", true);
}
else
{
GoogleConnect.Authorize("https://www.googleapis.com/auth/drive.readonly");
}
Can someone please help me to resolve the issue?

I'm not a C# developer, but if you're using Google.Apis.Drive.v3, then that is the latest version of the Google Drive API. I don't see any part of your code that references the Google APIs Client Library for .NET, but that's the recommended way to talk to modern Google APIs.
If you've installed it, take a look at the C# quickstart sample for the Drive API. Then check out the C#/.NET examples on the Download Files page in the docs, and it should lead you to a working solution. In your other comment, you asked about passing auth tokens, so if you're using the client library, you shouldn't have to worry about that part. On that docs page, you'll find a sample for regular file downloads and another for exporting Google documents (Docs, Sheets, Slides).
Finally, for additional reference, here are the .NET reference docs for the Drive API and the .NET Google APIs Client Library developers guide.

Related

How to upload to OneDrive using Microsoft Graph Api in c#

I have been trying to upload to a OneDrive account and I am hopelessly stuck not being able to upload neither less or greater than 4MB files. I have no issues accessing the drive at all, since I have working functions that create a folder, rename files/folders, and a delete files/folders.
https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=csharp
This documentation on Microsoft Graph API is very friendly to HTTP code, and I believe I am able to fairly "translate" the documentation to C#, but still fail to grab a file and upload to OneDrive. Some places online seem to be using byte arrays? Which I am completely unfamiliar with since my primary language is C++ and we just use ifstream/ofstream. Anyways, here is the portion of code in specific (I hope this is enough):
var item = await _client.Users[userID].Drive.Items[FolderID]//"01YZM7SMVOQ7YVNBXPZFFKNQAU5OB3XA3K"].Content
.ItemWithPath("LessThan4MB.txt")//"D:\\LessThan4MB.txt")
.CreateUploadSession()
.Request()
.PostAsync();
Console.WriteLine("done printing");
As it stands, it uploads a temporary file that has a tilde "~" in the OneDrive (like as if I was only able to open but not import any data from the file onto it). If I swap the name of the file so it includes the file location it throws an error:
Message: Found a function 'microsoft.graph.createUploadSession' on an open property. Functions on open properties are not supported.
Try this approach with memory stream and PutAsync<DriveItem> request:
string path = "D:\\LessThan4MB.txt";
byte[] data = System.IO.File.ReadAllBytes(path);
using (Stream stream = new MemoryStream(data))
{
var item = await _client.Me.Drive.Items[FolderID]
.ItemWithPath("LessThan4MB.txt")
.Content
.Request()
.PutAsync<DriveItem>(stream);
}
I am assuming you have already granted Microsoft Graph Files.ReadWrite.All permission. Check your API permission. I tested this code snippet with pretty old Microsoft.Graph library version 1.21.0. Hopefully it will work for you too.

Get a file from a plugin in Microsoft Dynamics 365

I´ve installed Dynamics Version 1612 (8.2.2.112) (DB 8.2.2.112) on-premises. I wrote a plugin to connect to a web API, work perfect, now I need to add more situations. The API can return an url to a zipped file with the response in a JSON file. Well, there're any change to point me in the right direction? First, to get the file. STFW so far he gave me no clue. Thanks in advance.
If you have an URL then get unzip and process.
Example how to get and unzip file.
WebClient wc = new WebClient();
using (MemoryStream stream = new MemoryStream(wc.DownloadData("URL")))
{
using (var zip = new ZipArchive(stream, ZipArchiveMode.Read))
{
...
}
}

Using Google Drive .NET API with UWP App

I am attempting to use Google Drive as a storage location in my UWP application. I started at the quickstart provided by Google. I copy the code into a blank UWP project, change some of the output code (Console.Writeline to a textbox.append method) and I try to build it. It fails to build and reports the error:
Cannot find type System.ComponentModel.ExpandableObjectConverter in module System.dll
I am running Windows 10 and VS 2015 and I have installed the sdk through NuGet. The example code in the quickstart does work in a console application. It is the UWP application that is having issues.
For the UWP application, I put the quickstart code in a button click method. This was because the API actually has an async method for the uwp apps which is a bit different then the code given in the quickstart.
Includes:
using System;
using System.Collections.Generic;
using System.IO;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.Threading;
The Button Method:
private async void button_Click(object sender, RoutedEventArgs e)
{
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = ""; //System.Environment.GetFolderPath(
//System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/client_secrets.json"),
Scopes,
"user",
CancellationToken.None);
//Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 10;
listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
.Files;
textBox.Text += "Files:\n";
if (files != null && files.Count > 0)
{
foreach (var file in files)
{
textBox.Text += (file.Name + file.Id + "\n");
}
}
else
{
textBox.Text += ("No files found.");
}
}
The test code will not work once the app is compiled as it is missing the code to load the client secret. Since I have not been able to test the code, this is all I can provide.
There is another post that is semi-related except that the answer is just that it wont work and the post has been dead for 4 years. I also wanted to create a new post that tags the google team specifically (like the quickstart says to do).
My specific question is: Is there a work around to this issue or am I just doing this wrong?
I agree with #Vincent, UWP apps use COM as a base and builds from there. Not all .Net API can be used in UWP apps, this SDK is based on .Net APIs, this is why your console app is OK, but your UWP app is down. For the differences between them, here is a great answer which explain this issue. But,
"You will need an UWP SDK from Google to build an UWP applications."
I just tried to search for this without any luck, but here is a suggestion, you can use JavaScript to make request to the Drive API. To do this, you can refer to JavaScript Quickstart. Then you can turn it to a web hosted UWP app, for more information, you can refer to Convert your web application to a Universal Windows Platform (UWP) app.
Another suggestion which can probably make the work easier is using Rest API to send HTTP requests, you can also refer to API Reference.
The final suggestion which is as #Vincent said, if you have access to the SDK code, you can also try to adapt it for UWP. It means you need to modify the source code of this SDK.
The .Net flavor used to build Windows Store/UWP apps has less features than the full .Net framework. Unfortunately, the ExpandableObjectConverter object is not available for UWP applications.
You will need an UWP SDK from Google to build an UWP applications.
If you have access to the SDK code, you can also try to adapt it for UWP.

Google Drive Sdk .net upload and download [duplicate]

My requirement is to upload a single file which will be selected by the user during runtime to Google drive. I am getting email id and password from user. How to do it? If i any other requirement get from users? any feasible solution is there?
You can use the Google Drive SDK/API, it's fairly simple stuff if you read through the documentation,
https://developers.google.com/drive/
https://developers.google.com/drive/manage-uploads
There's a .NET API available for download, although it's in beta I've used it without problem.
https://developers.google.com/drive/downloads
DocumentsService myService = new DocumentsService("application name");
myService.setUserCredentials("email", "password");
DocumentEntry newEntrys = myService.UploadDocument("pdf path", #"upload file name");
But I have take exception
Execution of request failed: https://docs.google.com/feeds/default/private/full?convert=false

Index pdf documents in Solr from C# client

Basically I'm trying to index word or pdf documents in Solr and found the ExtractingRequestHandler, but can't figure out how to write code in c# that performs the HTTP POST request like in the Solr wiki: http://wiki.apache.org/solr/ExtractingRequestHandler.
I've installed Solr 3.4 on Tomcat 7 (7.0.22) using the files from the example/solr directory in the Solr zip and I haven't altered anything. The ExtractingRequestHandler should be configured out of the box in the solrconfig.xml and ready to use, right?
Can some of you give an C# (HttpWebRequest) example of how you make the HTTP POST request and upload a PDF file like it is done using curl in the Solr wiki?
I've look all over this site and many others trying to find an example or a tutorial on how this is done, but haven't found anything.
EDIT:
I finally managed to get it to work using SolrNet!
In order for it to work you need to copy this to a lib-folder in your Solr installation directory from the Solr zip:
apache-solr-cell-3.4.0.jar file from the dist folder
content of contrib\extraction\lib directory
With SolrNet 0.4.0 beta 2, this code does the job:
Startup.Init<IndexDocument>("YOUR-SOLR-SERVICE-PATH");
var solr = ServiceLocator.Current.GetInstance<ISolrOperations<IndexDocument>>();
using (FileStream fileStream = File.OpenRead("FILE-PATH-FOR-THE-FILE-TO-BE-INDEXED"))
{
var response =
solr.Extract(
new ExtractParameters(fileStream, "doc1")
{
ExtractFormat = ExtractFormat.Text,
ExtractOnly = false
});
}
solr.Commit();
Sorry for the trouble. I hope however that others will find this useful.
I would recommend using the SolrNet client. It supports the ExtractingRequestHandler.

Categories