I have successfully uploaded image file in google drive using C#. But i am facing problem in uploading mp3 file on drive.
How I upload mp3 file in Google drive using C# in MVC?
this my Code for save file:
public ServieResponse SaveFileOnGoogleDrive(string url)
{
//string url = string.Empty; ; ;
//string[] scopes = new string[] { DriveService.Scope.Drive,
// DriveService.Scope.DriveFile};
string[] scopes = new string[] { DriveService.Scope.Drive,
DriveService.Scope.DriveAppdata,
//DriveService.Scope.DriveAppsReadonly,
DriveService.Scope.DriveFile,
DriveService.Scope.DriveMetadataReadonly,
DriveService.Scope.DriveReadonly,
DriveService.Scope.DriveScripts };
var clientId = "xxxxxx"; // From https://console.developers.google.com
var clientSecret = "xxxxxxx";
// From https://console.developers.google.com
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
},
scopes,
Environment.UserName,
CancellationToken.None,
new FileDataStore("MyAppsToken")).Result;
//Once consent is recieved, your token will be stored locally on the AppData directory, so that next time you wont be prompted for consent.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "CTM",
});
string filePath = WebConfigurationManager.AppSettings["filPath"];
filePath = HttpContext.Current.Server.MapPath(filePath) + url;
uploadFile(service, filePath, "", "");
// service.HttpClient.Timeout = TimeSpan.FromMinutes(100);
//Long Operations like file uploads might timeout. 100 is just precautionary value, can be set to any reasonable value depending on what you use your service for.
//return Json(new { result = "abc" }, JsonRequestBehavior.AllowGet);
ServieResponse ob = new ServieResponse();
ob.ResponseMsg = "Success";
return ob;
}
Now my code is working fine. Updated code is:
public ServieResponse SaveFileOnGoogleDrive(string url)
{
//string url = string.Empty; ; ;
//string[] scopes = new string[] { DriveService.Scope.Drive,
// DriveService.Scope.DriveFile};
string[] scopes = new string[] { DriveService.Scope.Drive,
DriveService.Scope.DriveAppdata,
//DriveService.Scope.DriveAppsReadonly,
DriveService.Scope.DriveFile,
DriveService.Scope.DriveMetadataReadonly,
DriveService.Scope.DriveReadonly,
DriveService.Scope.DriveScripts };
var clientId = "65675933715-poet7f7dhjhrmccmalhb41pltho7tusr.apps.googleusercontent.com"; // From https://console.developers.google.com
var clientSecret = "D8USyz3Pf82wOMi6l2pJehjx";
// From https://console.developers.google.com
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
},
scopes,
Environment.UserName,
CancellationToken.None,
new FileDataStore("MyAppsToken")).Result;
//Once consent is recieved, your token will be stored locally on the AppData directory, so that next time you wont be prompted for consent.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "CTM",
});
string filePath = WebConfigurationManager.AppSettings["filPath"];
filePath = HttpContext.Current.Server.MapPath(filePath) + url;
uploadFile(service, filePath);
ServieResponse ob = new ServieResponse();
ob.ResponseMsg = "Success";
return ob;
}
public static void uploadFile(DriveService _service, string _uploadFile)
{
if (System.IO.File.Exists(_uploadFile))
{
var body = new Google.Apis.Drive.v3.Data.File();
//File body = new File();
body.Name = System.IO.Path.GetFileName(_uploadFile);
//body.Description = _descrp;
body.MimeType = GetMimeType(_uploadFile);
// body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };
FilesResource.CreateMediaUpload request;
try
{
using (var stream = new System.IO.FileStream(_uploadFile, System.IO.FileMode.Open))
{
request = _service.Files.Create(body, stream, body.MimeType);
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
var fili = file.Id;
}
catch (Exception e)
{
}
}
else
{
}
}
private static string GetMimeType(string fileName)
{
string mimeType = "application/unknown";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
mimeType = regKey.GetValue("Content Type").ToString();
return mimeType;
}
Related
I want to get a list of names of files from Google Drive but I get an empty list each time
I created a project on Google Console
I enabled Google Drive API
I created a user in OAuth consent screen
I created credentials OAuth 2.0 Client IDs and downloaded it as json
namespace ConsoleApp4
{
class Program
{
static string[] Scopes = { DriveService.Scope.Drive };
static string ApplicationName = "TestGoogleDriveAPI";
private static UserCredential GetCredentials()
{
using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = Directory.GetCurrentDirectory();
credPath = Path.Combine(credPath, "drive-dot-net-quickstart.json");
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, false)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
return credential;
}
}
static void Main(string[] args)
{
UserCredential credential = GetCredentials();
// 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.Q = "name contains 'EMR_backup_' and createdTime > '2020-12-01T12:00:00' and modifiedTime > '2021-07-01T12:00:00'";
//listRequest.Q = "parents in '10ybGwqq7J_GbA7JvG6C8aiTFNRsdzdk7'";
//listRequest.PageSize = 10;
//listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
//FileList result = listRequest.Execute();
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
if (files != null && files.Count > 0)
{
foreach (var file in files)
{
Console.WriteLine("{0} ({1})", file.Name, file.Id);
}
}
else
{
Console.WriteLine("No files found.");
}
Console.Read();
}
}
}
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();
}
}
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..
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("=", "");
}
I used code for upload for console application.
its working but for web client api.. its not working for web application ...
I got null for Responsebody=null.
here is my code:
ClientSecrets secrets = new ClientSecrets()
{
ClientId = parameters.ClientId,
ClientSecret = parameters.ClientSecret
};
var token = new TokenResponse { RefreshToken = parameters.RefreshToken };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets
}),
Environment.UserName,
token);
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "Google Drive",
});
if (FileUpload1.HasFile)
{
var filename = FileUpload1.FileName;
var filepath = FileUpload1.PostedFile.FileName;
Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
body.Title = filename;
body.Description = "Documents";
body.MimeType =GetMimeType(filename);
body.Parents = new List<ParentReference>() { new ParentReference() { Id = "0BySorYm3rcaNeXV2Y0M5bXh1WjA" } };
//byte[] array = System.IO.File.ReadAllBytes(filepath);
MemoryStream stream = new MemoryStream(FileUpload1.FileBytes);
FilesResource.InsertMediaUpload fileuploadrequest = new FilesResource.InsertMediaUpload(service, body, stream, GetMimeType(filename));
//var name=MediaFileSource.GetContentTypeForFileName(filename);
//fileuploadrequest.Convert = true;
//fileuploadrequest.OauthToken=parameters.AccessToken;
fileuploadrequest.Upload();
//geting null using this code and also not getting error for upload
Google.Apis.Drive.v2.Data.File response = fileuploadrequest.ResponseBody;