c# google drive upload file - c#

Hi I want to upload file google drive but every time ,
I have this error Object reference not set to an instance of an object. I do every think this video series link.I accepted google drive upload request.
I tried zip , jpg, txt upload but same error.
And I try Google.Apis.Drive.v2 but same error.
What can I do? Please help sorry my English :(
private static string ApplicationName = "MysqlYedekleme";
private static string FolderId = "1g_PTi5lQBCbZBax_3foZPdiECOC7cSaU";
private static string filename = "test.rar";
private static string filePath = #"E:\yedekdeneme\test.rar";
private static string contentType = "application/zip";
//drve
private void Form1_Load(object sender, EventArgs e)
{
UserCredential credential = GetUserCredential();
DriveService service = GetDriveService(credential);
uploadFileDrive(service, filename, filePath, contentType);
}
private static UserCredential GetUserCredential()
{
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string creadPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
creadPath = Path.Combine(creadPath, "driveApiCredentials", "drive-credentials.json");
return GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"User",
CancellationToken.None,
new FileDataStore(creadPath, true)).Result;
}
}
private static DriveService GetDriveService(UserCredential credential)
{
return new DriveService
(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
private static string uploadFileDrive(DriveService service, string filename, string filePath, string contentType)
{
try
{
var fileMetadata = new Google.Apis.Drive.v3.Data.File();
fileMetadata.Name = Path.GetFileName(filePath);
fileMetadata.MimeType = "application/zip";
fileMetadata.Parents = new List<string> { FolderId };
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open))
{
request = service.Files.Create(fileMetadata, stream, contentType);
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
return file.Id;
}
catch (Exception exc)
{
System.Diagnostics.Debug.WriteLine("geldi:"+exc.Message);
}
}

Related

How to create folders in google drive without duplicate using c#?

I am trying to create a folder on my google drive and check if it already exists. I am new to c#, so I wrote a code to create a specific folder in which I can upload my CSV files, but each time my application runs, it creates a duplicate folder with same name and I am now trying to figure out how to stop it.
class GoogleApi
{
private string[] Scopes = { DriveService.Scope.Drive };
private string ApplicationName;
private string FolderId;
private string FileName;
private string FilePath;
private string ContentType;
public GoogleApi(string fileName, string filePath)
{
ApplicationName = "MantisToDrive";
ContentType = "text/csv";
FileName = fileName;
FilePath = filePath;
}
public void Upload()
{
UserCredential credential = GetCredentials();
DriveService service = GetDriveService(credential);
FolderId = CreateFolderToDrive(service, "MantisData");
UploadFileToDrive(service, FileName, FilePath, ContentType);
}
private DriveService GetDriveService(UserCredential credential)
{
return new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
//verify User Credentials using client_secret.json file
private UserCredential GetCredentials()
{
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 = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath , true)).Result;
}
return credential;
}
private string UploadFileToDrive(DriveService service, string fileName, string filePath, string contentType)
{
var fileMatadata = new Google.Apis.Drive.v3.Data.File();
fileMatadata.Name = fileName;
fileMatadata.Parents = new List<string> { FolderId };
FilesResource.CreateMediaUpload request;
using (var stream = new FileStream(filePath, FileMode.Open))
{
request = service.Files.Create(fileMatadata, stream, contentType);
//service.Files.Delete(fileName).Execute();
request.Upload();
}
var file = request.ResponseBody;
return file.Id;
}
// creating folder in google drive to store CSV
public static string CreateFolderToDrive(DriveService service, string folderName)
{
bool exists = Exists(service,folderName);
if (exists)
return $"Sorry but the file {folderName} already exists!";
var file = new Google.Apis.Drive.v3.Data.File();
file.Name = folderName;
file.MimeType = "application/vnd.google-apps.folder";
var request = service.Files.Create(file);
request.Fields = "id";
var result = request.Execute();
return result.Id;
}
private static bool Exists(DriveService service, string name)
{
var listRequest = service.Files.List();
listRequest.PageSize = 100;
listRequest.Q = $"trashed = false and name contains '{name}' and 'root' in parents";
listRequest.Fields = "files(name)";
var files = listRequest.Execute().Files;
foreach (var file in files)
{
if (name == file.Name)
return true;
}
return false;
}
}
This should work (this checks whether the folder exists in your root folder. If not, the method will create a folder):
public static string CreateFolder(string folderName)
{
bool exists = Exists(folderName);
if (exists)
return $"Sorry but the file {folderName} already exists!";
var file = new Google.Apis.Drive.v3.Data.File();
file.Name = folderName;
file.MimeType = "application/vnd.google-apps.folder";
var request = service.Files.Create(file);
request.Fields = "id";
return request.Execute().Id;
}
private static bool Exists(string name)
{
var listRequest = service.Files.List();
listRequest.PageSize = 100;
listRequest.Q = $"trashed = false and name contains '{name}' and 'root' in parents";
listRequest.Fields = "files(name)";
var files = listRequest.Execute().Files;
foreach (var file in files)
{
if (name == file.Name)
return true;
}
return false;
}
In case somebody comes here from the future and the pastebin link is dead. This is how you can upload a file to your google drive:
public static async Task UploadFileAsync(string fileName)
{
var file = new Google.Apis.Drive.v3.Data.File();
file.Name = Path.GetFileName(fileName);
file.Parents = new List<string> {folderID};
byte[] byteArray = System.IO.File.ReadAllBytes(fileName);
using (System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray))
{
await service.Files.Create(file, stream, "some mime type").UploadAsync();
}
}

uploading a file into google drive

I am trying to upload a file into my drive but the response is always null
i created a developer account then i got my api key and my client secret and id
but i still think that the problem is in the authentication step
static string ApplicationName = "WebApi";
private static readonly IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "my_client_ID",
ClientSecret = "my_client_secret",
},
Scopes = new[] { DriveService.Scope.Drive,
DriveService.Scope.DriveAppdata,
DriveService.Scope.DriveFile,
DriveService.Scope.DriveMetadataReadonly,
DriveService.Scope.DriveReadonly,
DriveService.Scope.DriveScripts},
DataStore = new FileDataStore("Drive.Api.Auth.Store")
});
public MainWindow()
{
InitializeComponent();
var service = new DriveService(new Google.Apis.Services.BaseClientService.Initializer()
{
ApiKey = "my_api_key",
HttpClientInitializer = flow as UserCredential,
ApplicationName = ApplicationName
});
insertFile(service, "file_name.mdf", "", "", "application/octet-stream", "file_name.mdf");
}
private static Google.Apis.Drive.v2.Data.File insertFile(DriveService service, String title, String description, String parentId, String mimeType, String filename)
{
// File's metadata
Google.Apis.Drive.v2.Data.File body = new
Google.Apis.Drive.v2.Data.File();
body.Title = title;
body.Description = description;
body.MimeType = mimeType;
body.Parents = body.Parents = new List<ParentReference>();
// Set the parent folder.
if (!String.IsNullOrEmpty(parentId))
{
body.Parents = new List<ParentReference>()
{new ParentReference() {Id = parentId}};
}
// File's content.
byte[] byteArray = System.IO.File.ReadAllBytes(filename);
MemoryStream stream = new MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream,mimeType );
request.Upload();
Google.Apis.Drive.v2.Data.File file = request.ResponseBody;
// Uncomment the following line to print the File ID.
Console.WriteLine("File ID: " + file.Id);
return file;
}
catch (Exception e)
{
throw e;
}
}
i am creating the service in the main window the i am trying to insert
the file in the insert file function
i am getting a null response please help..

Getting an 'UnauthorizedAccessException' when try to download a file from Google Drive using c# code

I am trying to download a file from Google Drive using the following code.
when it reach SaveStream() function it throwing an UnauthorizedAccessException.
As per some suggesstions I set the access permissions of that folder to Full control.But its not working for me now also I am getting the 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);
}
}
}
}

Send Google Mail in C# failed because of 403 Insufficient permissions

I created a console application which sends an email to an address, it shows like:
private static string[] Scopes = { GmailService.Scope.GmailCompose, GmailService.Scope.GmailSend };
private static string ApplicationName = "Gmail API Quickstart";
private const string SUBJECT = "Some simple subject";
private static string[] emails = new string[] { "teodorescumihail2008#live.com" };
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = Environment.GetFolderPath(
Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/gmail-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 Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
var msg = new AE.Net.Mail.MailMessage
{
Subject = SUBJECT,
Body = "Test body",
From = new MailAddress("teodorescumihail2008#gmail.com")
};
msg.To.Add(new MailAddress("teodorescumihail2008#live.com"));
StringWriter sw = new StringWriter();
msg.Save(sw);
var result = service.Users.Messages.Send(new Message
{
Raw = Base64UrlEncode(sw.ToString())
}, "me").Execute();
Console.Read();
}
private static string Base64UrlEncode(string input)
{
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
// Special "url-safe" base64 encode.
return Convert.ToBase64String(inputBytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
}
When execute sending email, I received:
Where is my mistake ?
I assumed you changed your scope in the code without reauthorize/getting a new credential file from Gmail. The problem is GmailAPI does not know that your scope is updated. You have to reauthorize your app in GmailAPI by deleting your app permission and regenerate your credentials.json so that your scope is updated on GmailAPI.
To delete your app permission: click here

How To create an instance of Google BaseClientService.Initializer

I want to know how to create an instance of Google BaseClientService.Initializer. I need to use the BaseClientService.Initializer to create the GmailService instance, and then use this GmailService instance to create an UsersResource instance.
Google.Apis.Services.BaseClientService.Initializer initializer = new BaseClientService.Initializer();
initializer.ApiKey = "MyApiKey";
initializer.ApplicationName = "MyProject";
initializer.DefaultExponentialBackOffPolicy = Google.Apis.Http.ExponentialBackOffPolicy.None;
Google.Apis.Gmail.v1.GmailService gmailService = new GmailService(initializer);
Google.Apis.Gmail.v1.UsersResource usersResource = new UsersResource(gmailService);
UsersResource.MessagesResource messagesResource = usersResource.Messages;
First go to the link bellow and open an application in your google account.
once you run the code you'll get exception for the first time, given you an address to go and enable the API in your google account.
https://console.developers.google.com/apis/dashboard?project=super-pharm-log-notifications
static string[] Scopes = { GmailService.Scope.GmailCompose, GmailService.Scope.GmailSend, GmailService.Scope.GmailInsert };
static private BaseClientService.Initializer initializeGmailAccountServices()
{
string appRoot = null;
if (System.Web.HttpContext.Current == null)
{
appRoot = Environment.CurrentDirectory;
}
else
{
appRoot = System.Web.HttpContext.Current.Server.MapPath(#"~\");
}
string path = Path.Combine(appRoot, DBConstants.GMAIL_CREDENTIALS_PATH);
UserCredential credential;
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
ClientSecrets secrets = GoogleClientSecrets.Load(stream).Secrets;
var t = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, Scopes, "user", CancellationToken.None);
t.Wait();
credential = t.Result;
}
return= new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "your application name",
};
}
private static string Base64UrlEncode(string input)
{
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
// Special "url-safe" base64 encode.
return Convert.ToBase64String(inputBytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
}

Categories