I am trying to upload a JPG from my local drive to Google Drive. I set up OAuth 2.0 Client IDs on Google Clouds APIs and Services. I added Everyone group to that folder. Also, grant full control permission. But, it still throws the following error when I run the program.
"Exception has occurred: CLR/System.UnauthorizedAccessException An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.Private.CoreLib.dll: 'Access to the path 'c:\folderName' is denied.'
The error throws on the following line
using (var stream = new FileStream(filePath,
FileMode.Open))
{
// Create a new file, with metadata and stream.
request = service.Files.Create(
fileMetadata, stream, "image/jpeg");
request.Fields = "id";
request.Upload();
}
Thank you for your help.
Here is my code:
namespace DocUploader
{
class Program
{
static string[] Scopes = { DriveService.Scope.Drive };
static string ApplicationName = "App Name";
static string filePath = "c:\\folderName";
static void Main(string[] args)
{
try
{
UserCredential credential;
// Load client secrets.
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(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
});
// Upload file photo.jpg on drive.
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = "photo.jpg"
};
FilesResource.CreateMediaUpload request;
// Create a new file on drive.
using (var stream = new FileStream(filePath,
FileMode.Open))
{
// Create a new file, with metadata and stream.
request = service.Files.Create(
fileMetadata, stream, "image/jpeg");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
// Prints the uploaded file id.
Console.WriteLine("File ID: " + file.Id);
}
catch (Exception e)
{
if (e is AggregateException)
{
Console.WriteLine("Credential Not found");
}
else if (e is FileNotFoundException)
{
Console.WriteLine("File not found");
}
else
{
throw;
}
}
}
}
}