Jump to content

Recommended Posts

Chào các bạn, hôm nay mình có một tools liên quan đến google drive, nên tiện nghiên cứu được chút nào thì cũng up lên đây làm tư liệu cho các bạn chưa tìm hiểu cần tìm hiểu :c04:. Mình vào chủ đề luôn nhé.

Yêu cầu :

Quote
  1. Tài khoản gmail, đã enable goog drive api
  2. Tạo Credentials -> Oauth 2.0 ở đây https://console.cloud.google.com -> tải file .json về nhé.
  3. Visual studio 2017 trở lên, máy đã cài .Net Framework 4.5 trở lên

Oke giờ bắt đầu mình là sổ code thôi :c07:

Bước 1 : Sử dụng file .json để cấp quyền truy cập, chỉnh sửa, xóa trên drive google bằng code sau :

string[] Scopes = { DriveService.Scope.Drive};
UserCredential credential;
string DuongDanChuaFileJson = @"ClientSecrectFile.json"; // Thay đường dẫn cho đúng nhé
using (var stream = new FileStream(JsonPathFile, 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 = "token.json"; // Sau khi cấp quyền xong thì sẽ lưu token ở đây
     credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                  GoogleClientSecrets.Load(stream).Secrets,
                  Scopes,
                  "user",
                  CancellationToken.None,
                  new FileDataStore(credPath, true)).Result;
      MessageBox.Show("Credential file saved to: " + credPath);
}
DriveService service = new DriveService(new BaseClientService.Initializer()
{
      HttpClientInitializer = credential,
      ApplicationName = "Google Drive Api v3",
});

Nếu không có gì sai thì  sẽ xuất hiện dòng thông báo nơi lưu file token.json.
*Chú ý : lần đầu tiên bạn sẽ bị google bắt đăng nhập vào tài khoản gmail và cấp phép cho việc sử dung drive google, cứ bấm oke và cho phép thôi :), Lần sau thì bạn sẽ chỉ thấy thông báo nơi lưu file token.json

Bước 2 : Khai báo cấp quyền xong, các bạn sẽ thao tác được với mọi file trong google drive của bạn. Ví dụ như :

2.1 - Lấy số lượng file và folder có trong google drive :

FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 30; // Số lượng file muốn lấy
listRequest.Fields = "nextPageToken, files(id, name)";
listRequest.IncludeItemsFromAllDrives = false;
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
string AllFileNameID = "";
if (files != null && files.Count > 0)
{
    foreach (var file in files)
    {
        AllFileNameID += file.Name + " : " + file.Id + "\n";
    }
    MessageBox.Show(AllFileNameID); // có file
}
else
{
    MessageBox.Show("No files found."); // không có file nào
}

2.2 - Lấy số lượng folder có trong google drive :

FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 30; // Số lượng file muốn lấy
listRequest.Fields = "nextPageToken, files(id, name)";
listRequest.Q = "mimeType = 'application/vnd.google-apps.folder'"; //sử dụng để chỉ lấy kết quả folder 
listRequest.IncludeItemsFromAllDrives = false;
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
string AllFileNameID = "";
if (files != null && files.Count > 0)
{
    foreach (var file in files)
    {
        AllFileNameID += file.Name + " : " + file.Id + "\n";
    }
    MessageBox.Show(AllFileNameID); // có folder
}
else
{
    MessageBox.Show("No files found."); // không có folder nào
}

2.3 - Lấy toàn bộ file có trong google drive :

FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 30; // Số lượng file muốn lấy
listRequest.Fields = "nextPageToken, files(id, name)";
listRequest.Q = "mimeType != 'application/vnd.google-apps.folder'"; //sử dụng để chỉ lấy kết quả folder 
listRequest.IncludeItemsFromAllDrives = false;
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
string AllFileNameID = "";
if (files != null && files.Count > 0)
{
    foreach (var file in files)
    {
        AllFileNameID += file.Name + " : " + file.Id + "\n";
    }
    MessageBox.Show(AllFileNameID); // có folder
}
else
{
    MessageBox.Show("No files found."); // không có folder nào
}

2.4 - Tạo thư mục :

Google.Apis.Drive.v3.Data.File fileMetadata = new Google.Apis.Drive.v3.Data.File
{
    Name = TbFolderCreat.Text,
    MimeType = "application/vnd.google-apps.folder"
};
Google.Apis.Drive.v3.FilesResource.CreateRequest request = service.Files.Create(fileMetadata);
request.Fields = "id";
Google.Apis.Drive.v3.Data.File FolderMoi = request.Execute();
service.Files.Create(fileMetadata).Fields = "id";
MessageBox.Show(FolderMoi.Id);
Clipboard.SetText(FolderMoi.Id);

2.5 - Tải file lên thư mục :

 Google.Apis.Drive.v3.Data.File fileMetadata = new Google.Apis.Drive.v3.Data.File
{
    Name = System.IO.Path.GetFileName("Tên file upload"),
    MimeType = Contentype_Upload,
    //Parents = new List<string> { "ID Folder" }, //Muốn up file vào thư mục nào thì phải lấy folder ID của thư mục đó bỏ vào đây nhé
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream("Path file upload",
System.IO.FileMode.Open))
{
    request = service.Files.Create(fileMetadata, stream, Contentype_Upload); // Contentype_Upload = "image/jepg đối với ảnh
                                                                             //Contentype_Upload = "video/mp4" đối với video
                                                                             //Contentype_Upload = ".../..." đối với file nén (mình quên rồi :D)
    request.Fields = "id";
    request.Upload();
}
Google.Apis.Drive.v3.Data.File Filemoi = request.ResponseBody;
//MessageBox.Show(Filemoi.Id);
Clipboard.SetText(Filemoi.Id); // Kết quả trả về ID của file
service.Dispose();

2.6 - Xóa file, thư mục :

2.7 - Đổi tên và di chuyển folder, file :

Chia sẻ bài đăng này


Link tới bài viết
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Trả lời chủ đề này...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...