# ASP.NET MVC C# 使用Google API服務
###### tags: `Microsoft` `Google` `ASP.NET` `ASP.NET MVC` `Google API`
## 一、啟用Google Api服務
[Google Api服務](https://console.cloud.google.com/apis/)
## 二、認證
OAuth跟服務帳戶擇一使用
OAuth適合需要使用者登入、檔案會存放於使用者自己的雲端硬碟
服務帳戶會將檔案存放於服務帳戶可存取(開發者)的雲端硬碟中
### 1.OAuth認證
#### (1) 建立憑證
* 建立API金鑰

* 建立 OAuth 用戶端 ID

* 紀錄產生後的用戶端 ID和用戶端密碼

#### (2) 取得授權
```csharp=
UserCredential credential;
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets {
ClientId = "用戶端 ID",
ClientSecret = "用戶端密碼",
},
new[] {
DocsService.Scope.Documents,
DriveService.Scope.Drive,
DriveService.Scope.DriveFile
},
"user",//如果只有一人, 可以使用任何固定字串, 例如: "user"
CancellationToken.None,
new FileDataStore(Server.MapPath("~/App_Data/Auth.Store"))//用來儲存 Token 的目錄
).Result;
```
#### (3) 使用授權
```csharp=+
var driveService = new DriveService(new Google.Apis.Services.BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Google Drive API .NET Quickstart"
});
```
### 2.使用服務帳戶
#### (1) 建立服務帳戶

#### (2) 新增金鑰、保存JSON檔案

#### (3) 取得授權
```csharp=
//從資料流讀取
GoogleCredential credential;
using (FileStream fs = new FileStream("credential.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(fs).CreateScoped(new[] { DriveService.Scope.Drive });
}
```
```csharp=
//方法2 從JSON字串讀取
string _credentialJson = string.Empty;
using (FileStream fs = new FileStream("credential.json", FileMode.Open, FileAccess.Read))
{
using (StreamReader sr = new StreamReader(fs, Encoding.Default))
{
_credentialJson = sr.ReadToEnd();
}
}
GoogleCredential credential = GoogleCredential.FromJson(_credentialJson).CreateScoped(new[] { DriveService.Scope.Drive });
```
#### (4) 使用授權
```csharp=
DriveService _driveService = new DriveService(new Google.Apis.Services.BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "_applicationName"
});
DriveService _docsService = new DocsService(new Google.Apis.Services.BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "_applicationName"
});
```
## 三、Nuget安裝
Nuget 安裝 Google.Apis.Docs.v1、Google.Apis.Drive.v3

## 四、常用功能
### 1. 文件列表
```csharp=
List<Google.Apis.Drive.v3.Data.File> ListOfFiles = new List<Google.Apis.Drive.v3.Data.File>();
FilesResource.ListRequest listRequest = _driveService.Files.List();
listRequest.PageSize = 1000;
listRequest.Fields = "nextPageToken, files(id, name,parents,mimeType,size,capabilities,modifiedTime,webViewLink,webContentLink)";
FileList fileFeedList = listRequest.Execute();
while (fileFeedList != null)
{
foreach (Google.Apis.Drive.v3.Data.File file in fileFeedList.Files)
{
ListOfFiles.Add(file);
}
if (fileFeedList.NextPageToken == null)
{
break;
}
else
{
listRequest.PageToken = fileFeedList.NextPageToken;
fileFeedList = listRequest.Execute();
}
}
```
### 2. 複製文件
```csharp=+
Google.Apis.Drive.v3.Data.File copyFile = new Google.Apis.Drive.v3.Data.File()
{
Name = fileName,
MimeType = "application/vnd.google-apps.document",
DriveId = "_storeFolder", //資料夾ID
Parents = new List<string>() { "_storeFolder" },//necessary
};
FilesResource.CopyRequest copyRequest = _driveService.Files.Copy(copyFile, "docID");
copyRequest.Fields = "id,parents";
copyRequest.SupportsAllDrives = true;
copyRequest.Execute();
```
### 3. 刪除文件
```csharp=+
_driveService.Files.Delete("fileID").Execute();
```
### 4. 取代文字
```csharp=+
ReplaceAllTextRequest ratr1 = new ReplaceAllTextRequest();
ratr1.ContainsText = new SubstringMatchCriteria() { Text = "{{目標文字}}", MatchCase = false };
ratr1.ReplaceText = "取代文字";
ReplaceAllTextRequest ratr2 = new ReplaceAllTextRequest();
ratr2.ContainsText = new SubstringMatchCriteria() { Text = "{{date}}", MatchCase = false };
ratr2.ReplaceText = DateTime.Now.ToString();
List<Request> requestsMerge = new List<Request>();
requestsMerge.Add(new Request() { ReplaceAllText = ratr1 });
requestsMerge.Add(new Request() { ReplaceAllText = ratr2 });
BatchUpdateDocumentRequest bodyMerge = new BatchUpdateDocumentRequest() { Requests = requestsMerge };
_docsService.Documents.BatchUpdate(bodyMerge, "docID").Execute();
```
### 5. 新增權限
```csharp=+
Permission permission = new Permission();
permission.Type = "user"; //user,group,domain,anyone
permission.Role = "writer"; //owner,organizer,fileOrganizer,writer,commenter,reader
if (type == "user" || type == "group")
permission.EmailAddress = "email@gmail.com";
else if (type == "domain")
permission.Domain = "xxx.com.tw";
PermissionsResource.CreateRequest permissionCreateRequest = _driveService.Permissions.Create(permission, "docID");
permissionCreateRequest.Fields = "id";
permissionCreateRequest.Execute();
```
### 6. 移除權限
```csharp=+
PermissionsResource.GetRequest existPermission = _driveService.Permissions.Get("fileID", "permissionID");
if (existPermission != null)
{
PermissionsResource.DeleteRequest permissionDeleteRequest = _driveService.Permissions.Delete("fileID", "permissionID");
permissionDeleteRequest.Execute();
}
```