I want to upload the image on google drive using c# in mvc.
What I have tried:
My code is
<pre> string[] scopes = new string[] { DriveService.Scope.Drive,
DriveService.Scope.DriveFile};
var clientId = "clientid";
var clientSecret = "client Secret Key";
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
},
scopes,
Environment.UserName,
CancellationToken.None,
new FileDataStore("MyAppsToken")).Result;
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "application Name",
});
uploadFile(service, "D:\\img\\adv2.jpeg", "", "photos");
public static void uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!")
{
if (System.IO.File.Exists(_uploadFile))
{
var body = new Google.Apis.Drive.v3.Data.File();
body.Name = System.IO.Path.GetFileName(_uploadFile);
body.Description = _descrp;
body.MimeType = GetMimeType(_uploadFile);
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.CreateMediaUpload request;
try
{
using (var stream1 = new System.IO.FileStream(_uploadFile, System.IO.FileMode.Open))
{
request = _service.Files.Create(body, stream1, GetMimeType(_uploadFile));
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;
}
I am getting null in "file"
var file = request.ResponseBody;
.
please suggest me why file is not uploaded..