Getting an 'UnauthorizedAccessException' when try to download a file from Google Drive using c# code -
i trying download file google drive using following code. when reach savestream() function throwing unauthorizedaccessexception.
as per suggesstions set access permissions of folder full control.but not working me getting same exception.
namespace backend.controllers { public class googledrivecontroller : controller { // get: googledrive static string[] scopes = { driveservice.scope.drivereadonly }; static string applicationname = "drive api .net quickstart"; public actionresult index() { usercredential credential; using (var stream = new filestream(@"d:\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 = googlewebauthorizationbroker.authorizeasync( googleclientsecrets.load(stream).secrets, scopes, "user", cancellationtoken.none, new filedatastore(credpath, true)).result; // 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.maxresults = 10; ilist<google.apis.drive.v2.data.file> files = listrequest.execute().items; if (files != null && files.count > 0) { foreach (var file in files) { downloadfile(service, file, string.format(@"d:\photos")); } } return view(); } private static void downloadfile(google.apis.drive.v2.driveservice service, google.apis.drive.v2.data.file file, string saveto) { var request = service.files.get(file.id); var stream = new system.io.memorystream(); request.mediadownloader.progresschanged += (google.apis.download.idownloadprogress progress) => { switch (progress.status) { case google.apis.download.downloadstatus.downloading: { // (progress.bytesdownloaded); break; } case google.apis.download.downloadstatus.completed: { //"download complete."; savestream(stream, saveto); break; } case google.apis.download.downloadstatus.failed: { //"download failed."; break; } } }; request.download(stream); } private static void savestream(system.io.memorystream stream, string saveto) { using (system.io.filestream file = new system.io.filestream(saveto, system.io.filemode.create, system.io.fileaccess.write)) { stream.writeto(file); } } } }
Comments
Post a Comment