本文整理汇总了C#中DriveService类的典型用法代码示例。如果您正苦于以下问题:C# DriveService类的具体用法?C# DriveService怎么用?C# DriveService使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DriveService类属于命名空间,在下文中一共展示了DriveService类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetFileByID
private File GetFileByID(string fileID, DriveService service)
{
File file = service.Files.Get(fileID).Execute();
if (file.ExplicitlyTrashed == null)
return file;
return null;
}
示例2: GetDriveService
public static DriveService GetDriveService()
{
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
var credPath = Environment.GetFolderPath(
Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart");
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
});
return service;
}
示例3: ListDrive
public async Task<ActionResult> ListDrive(CancellationToken cancellationToken)
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "904595749350-0m2f89cjfmhq8a9pplo62njot4pk977a.apps.googleusercontent.com",
ClientSecret = "l6Inr8ki5h95x8QElYWxiwHS"
},
new[] { DriveService.Scope.Drive },
"user",
CancellationToken.None).Result;
//var ctx = Request.GetOwinContext();
//var result = ctx.Authentication.AuthenticateAsync("ExternalCookie").Result;
var service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = result,
ApplicationName = "ASP.NET MVC Sample"
});
var list = await service.Files.List().ExecuteAsync();
ViewBag.Message = "Files from google drive";
return View(list);
}
示例4: AuthenticateOauth
/// <summary>
/// 구글의 Oauth 2.0을 사용하여 유저 정보를 가져온다.
/// </summary>
/// <param name="clientId">Developer console에서 발급받은 userid</param>
/// <param name="clientSecret">Developer console에서 발급받은 보안 번호</param>
/// <param name="userName">사용자를 구별하기 위한 유저 이름 (닉네임)</param>
/// <returns></returns>
public static DriveService AuthenticateOauth(string clientId, string clientSecret, string userName)
{
//Google Drive scopes Documentation: https://developers.google.com/drive/web/scopes
string[] scopes = new string[] { DriveService.Scope.Drive, //Google 드라이브에서 파일 보기 및 관리
DriveService.Scope.DriveAppdata, //Google 드라이브에서 설정 데이터 조회 및 관리
DriveService.Scope.DriveAppsReadonly, // Google 드라이브 앱 조회
DriveService.Scope.DriveFile, // 이 앱으로 열거나 만든 Google 드라이브 파일과 폴더 조회 및 관리
DriveService.Scope.DriveMetadataReadonly, // Google 드라이브에서 파일의 메타데이터 보기
DriveService.Scope.DriveReadonly, // Google 드라이브에서 파일 보기
DriveService.Scope.DriveScripts }; // Google Apps Script 스크립트의 행동 변경
try
{
// 신규 유저 접근 권한을 받아오거나 혹은 저장되어 있는 (기본 위치 C:\Users\bit-user\AppData\Roaming\)에 토큰을 가지고 유저정보를 가져온다.
UserCredential credential = GoogleWebAuthorization.LoginAuthorizationCodeFlowAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, userName
, CancellationToken.None
, new FileDataStore("Daimto.Drive.Auth.Store")).Result;
// 받아온 유저의 정보를 이용하여 google drive 에 연결한다.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "GoogleCloude Sample",
});
return service;
}
catch (Exception ex)
{
return null;
}
}
示例5: ConnectToGoogleDrive
public static async Task<ConnectionResult> ConnectToGoogleDrive(Controller controller, CancellationToken token)
{
string userId = controller.User.Identity.GetUserId();
GoogleDriveService service = null;
if (ServiceCache.TryGetValue(userId, out service))
return new ConnectionResult(service, null);
var result = await new AuthorizationCodeMvcApp(controller, new AppFlowMetadata()).AuthorizeAsync(token);
if (result.Credential == null)
{
return new ConnectionResult(null, result.RedirectUri);
}
var Service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = GoogleDriveSettings.APP_NAME
});
service = new GoogleDriveService(new DriveDataService(Service));
ServiceCache[userId] = service;
return new ConnectionResult(service, null);
}
示例6: DriveDataService
public DriveDataService(DriveService connectionService)
{
if (connectionService == null)
throw new ArgumentNullException("connectionService == null");
ConnectionService = connectionService;
}
示例7: Create
public IDriveService Create()
{
const string applicationName = "GoogleDriveOfflineBackup";
var scopes = new[] { DriveService.Scope.DriveReadonly };
UserCredential credential;
Console.WriteLine("Searching for settings file");
CredentialsProvider credentialsProvider = new CredentialsProvider();
string secretFile = credentialsProvider.LocateSettingsFile();
using (var stream = new FileStream(secretFile, FileMode.Open, FileAccess.Read))
{
string personalPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string credentialsPath = Path.Combine(personalPath, ".credentials");
string appCredentialsPath = Path.Combine(credentialsPath, "GoogleDriveOfflineBackup");
Console.WriteLine("Authorizing {0}", appCredentialsPath);
var secrets = GoogleClientSecrets.Load(stream).Secrets;
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
secrets,
scopes,
"user",
CancellationToken.None,
new FileDataStore(appCredentialsPath, fullPath: true)).Result; // blocking!
Console.WriteLine("Credentials written to {0}", appCredentialsPath);
}
// create service
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = applicationName
});
return new DriveServiceWrapper(service);
}
示例8: InitService
public void InitService()
{
// Auth id and secret from google developers console
string clientId = "354424347588-6bb4q1o8ufba3fu32tknk8elep233s4g.apps.googleusercontent.com";
string clientSecret = "NOSdJs3FPwfyoI62A6sCrfjg";
//Scopes for use with the Google Drive API
string[] scopes = new string[]
{
DriveService.Scope.Drive
// ,DriveService.Scope.DriveFile
};
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
},
scopes,
Environment.UserName,
CancellationToken.None,
new FileDataStore(CredentialSavePath, true)).Result;
mDriveService = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = AppName,
});
}
示例9: subirArchivo
public void subirArchivo()
{
string ruta = @"C:\Users\addiaz\Desktop\DocumentosDrive\";
string nombre = FileUpload1.PostedFile.FileName;
string sExtension = ObtenerTipoArchivo(FileUpload1.FileName);
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "704651064787-6l6ce8uiculoenaqera0fa40kd53t6sn.apps.googleusercontent.com",
ClientSecret = "uonquuVkIoLXGWjhLSicKpUL",
},
new[] { DriveService.Scope.Drive }, "user", CancellationToken.None).Result;
// Servicio para realizar peticiones al google drive.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});
File body = new File();
body.Title = nombre;
body.Description = "A test document";
body.MimeType = sExtension;
// byte[] byteArray = System.IO.File.ReadAllBytes(Server.MapPath(nombre));
byte[] byteArray = System.IO.File.ReadAllBytes("C:/Users/Adrian/Desktop/DcomuentosDrive/" + nombre);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, sExtension);
request.Upload();
File file = request.ResponseBody;
}
示例10: Connect
public void Connect()
{
string[] Scopes = new string[] { DriveService.Scope.Drive,
DriveService.Scope.DriveFile};
string ApplicationName = "Drive API Quickstart";
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");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
//Console.WriteLine("Credential file saved to: " + credPath);
}
service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
listRequest = service.Files.List();
listRequest.MaxResults = 1000;
firstPageToken = listRequest.PageToken;
}
示例11: uploadFile
/// <summary>
/// Uploads a file
/// Documentation: https://developers.google.com/drive/v2/reference/files/insert
/// </summary>
/// <param name="_service">a Valid authenticated DriveService</param>
/// <param name="_uploadFile">path to the file to upload</param>
/// <param name="_parent">Collection of parent folders which contain this file.
/// Setting this field will put the file in all of the provided folders. root folder.</param>
/// <returns>If upload succeeded returns the File resource of the uploaded file
/// If the upload fails returns null</returns>
public static File uploadFile(DriveService _service, string _uploadFile, string _parent, string Description)
{
if (System.IO.File.Exists(_uploadFile))
{
File body = new File();
body.Name = System.IO.Path.GetFileName(_uploadFile);
body.Description = Description;
body.MimeType = GetMimeType(_uploadFile);
body.Parents = new List<string> { _parent };
// File's content.
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
var request = _service.Files.Create(body, stream, GetMimeType(_uploadFile));
//request.Convert = true; // uncomment this line if you want files to be converted to Drive format
request.Upload();
return request.ResponseBody;
}
catch (Exception)
{
return null;
throw;
}
}
else {
Console.WriteLine("File does not exist: " + _uploadFile);
return null;
}
}
示例12: uploadFile
public static String /*File*/ uploadFile(DriveService service, string localFilePath)
{
if (System.IO.File.Exists(localFilePath))
{
//File's body
File body = new File();
body.Title = System.IO.Path.GetFileName(localFilePath);
body.Description = "Uploaded by Popcorn-GDrive";
body.MimeType = GetMimeType(localFilePath);
//File content
byte[] byteArray = System.IO.File.ReadAllBytes(localFilePath);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, GetMimeType(localFilePath));
request.Upload();
//String fileID = request.ResponseBody.Id;
return request.ResponseBody.Id;
}
catch(Exception e)
{
throw;
}
}
else
{
return null;
}
}
示例13: AuthenticateOauth
public static DriveService AuthenticateOauth(string clientID, string clientSecret, string userName)
{
//Google Drive scopes Documentation: https://developers.google.com/drive/web/scopes
string[] scopes = new string[] { DriveService.Scope.Drive, //View and manage files and documents
DriveService.Scope.DriveAppdata, //View and manage its own configuration data
DriveService.Scope.DriveAppsReadonly, //View and manage drive apps
DriveService.Scope.DriveFile, //View and manage files created by Popcorn-GDrive
DriveService.Scope.DriveMetadataReadonly, //View metadata for files
DriveService.Scope.DriveReadonly, //View (only) files and documents on your drive
/*DriveService.Scope.DriveScripts,*/ //View your app scripts
};
try
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientID, ClientSecret = clientSecret }
, scopes
, userName
, CancellationToken.None
, new FileDataStore("Popcorn-GDrive.Auth.Store")).Result;
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Popcorn-GDrive",
});
return service;
}
catch (Exception e)
{
throw e;
//Console.WriteLine(e.InnerException);
}
}
示例14: AuthenticateServiceAccount
public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath, string applicationName)
{
if (!File.Exists(keyFilePath))
{
throw new FileNotFoundException("Given key file is not found", keyFilePath);
}
// Google Drive scopes Documentation: https://developers.google.com/drive/web/scopes
string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents
DriveService.Scope.DriveAppdata, // view and manage its own configuration data
DriveService.Scope.DriveAppsReadonly, // view your drive apps
DriveService.Scope.DriveFile, // view and manage files created by this app
DriveService.Scope.DriveMetadataReadonly, // view metadata for files
DriveService.Scope.DriveReadonly, // view files and documents on your drive
DriveService.Scope.DriveScripts }; // modify your app scripts
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
var credential =
new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scopes
}.FromCertificate(certificate));
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = applicationName,
});
return service;
}
示例15: catch
/* public Boolean DownloadFile(DriveService service, GFile _fileResource, string _saveTo)
{
try {
//File file = service.Files.Get(fileId).Execute();
FilesResource.GetRequest request = service.Files.Get(_fileResource.Id);
request.url
return true;
}
catch (Exception e) {
return false;
}
}*/
public Boolean DownloadFile(DriveService service, GFile _fileResource, string _saveTo)
{
GFile newFile = service.Files.Get(_fileResource.Id).Execute();
if (!String.IsNullOrEmpty(_fileResource.DownloadUrl))
{
using (FileStream fs = System.IO.File.Create(_saveTo))
{
//Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
var x = service.HttpClient.GetByteArrayAsync(newFile.DownloadUrl);
byte[] arrBytes = x.Result;
//fs.WriteAllBytes(_saveTo, arrBytes);
fs.Write(arrBytes, 0, arrBytes.Length);
//fs.WriteAsync()
//fs.Write(arrBytes, 0, arrBytes.Length);
return true;
}
}
else
{
// The file doesn't have any content stored on Drive.
//winform.AddText("Error2");
return false;
}
return false;
}