- [DEVEXPRESS] Hướng dẫn bật tính năng Scroll Pixcel in Touch trên GridView
- [DEVEXPRESS] Hướng dẫn sử dụng TileBar viết ứng dụng duyệt hình ảnh Winform
- [DEVEXPRESS] Tô màu border TextEdit trên Winform
- [C#] Lấy dữ liệu từ Console Write hiển thị lên textbox Winform
- [C#] Hiển thị Progress bar trên Window Console
- [C#] Di chuyển control Runtime và lưu layout trên winform
- [SQLSERVER] Sử dụng hàm NULL IF
- [C#] Chia sẽ source code mã đi tuần bằng giao diện Winform
- [C#] Flash Window in Taskbar Winform
- Download và Giải nén tập tin File sử dụng Powershell
- [C#] Hướng dẫn cách lấy thông tin đăng nhập tài khoản và mật khẩu web browser trên windows
- [VB.NET] CRUD Thêm xóa sửa tìm kiếm Realtime FireBase
- [C#] Hiển thị thông báo Toast Message trong lập trình Winform
- [C#] Cấu hình định dạng ngày tháng, thời gian trên Windows cho ứng dụng Winform
- [C#] Rút gọn đường dẫn link url với TinyURL API
- [C#] Hướng dẫn cách bo tròn winform with Radius
- [C#] Chia sẽ class BackGroundOverlay Show Modal cho Winform
- [C#] Hướng dẫn Flip Image Winform
- [C#] Invoke là gì? cách sử dụng phương thức Invoke()
- [C#] Hướng dẫn chia sẽ file, folder từ ứng dụng sang Zalo Chat
[C#] Hướng dẫn lấy danh sách, xóa, upload, download file Google Cloud Storage API
Xin chào các bạn bài viết hôm nay, mình sẽ tiếp tục chia sẽ đến các bạn các lấy danh sách, xóa, upload, download file từ Google Cloud Storage API C# Winform.
[C#] GET, DELETE, UPLOAD, DOWNLOAD FILE GOOGLE STORAGE CLOUD API
Cloud storage hay lưu trữ đám mây là một thuật ngữ dùng để chỉ các hành động lưu giữ, sắp xếp, quản lý, chia sẻ, và sao lưu dữ liệu của cá thể sở hữu nó trên một hệ thống lưu trữ bên ngoài ổ cứng được duy trì bởi các nhà cung cấp (hay bên thứ ba). Dịch vụ này cho phép khách hàng hay người dùng có thể truy cập được tất cả các tệp tin của họ từ xa tại bất kỳ vị trí địa lý nào.
Dịch vụ này cho phép khách hàng hay người dùng có thể truy cập được tất cả các tệp tin của họ từ xa tại bất kỳ vị trí địa lý nào.
Dưới đây là giao diện demo ứng dụng sử dụng Api: Google Storage Cloud C#
Trong bài viết này, mình có tích hợp các chức năng cơ bản để làm việc với cloud storage: Lấy danh sách, xóa, upload và download file có bất đồng bộ có progress Bar.
Source code Google Cloud Storage API C#:
using Google.Apis.Auth.OAuth2;
using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MimeMapping;
using Google.Apis.Upload;
using System.Threading;
using Google.Apis.Download;
using System.Collections;
namespace GoogleCloud
{
public partial class Form1 : Form
{
GoogleCredential credential = null;
string bucketName;
StorageClient storageClient;
public Form1()
{
InitializeComponent();
using (var jsonStream = new FileStream("laptrinhvb-c96be-e4ea5c001fd4.json", FileMode.Open,
FileAccess.Read, FileShare.Read))
{
credential = GoogleCredential.FromStream(jsonStream);
}
bucketName = "laptrinhvb-c96be.appspot.com";
storageClient = StorageClient.Create(credential);
}
private async void button1_Click(object sender, EventArgs e)
{
var dlg = new OpenFileDialog();
if(dlg.ShowDialog() == DialogResult.OK)
{
using (var fileStream = new FileStream(dlg.FileName, FileMode.Open,
FileAccess.Read, FileShare.Read))
{
progressBar1.Maximum = (int)fileStream.Length;
var uploadObjectOptions = new UploadObjectOptions
{
ChunkSize = UploadObjectOptions.MinimumChunkSize
};
var progressReporter = new Progress<IUploadProgress>(OnUploadProgress);
await storageClient.UploadObjectAsync(bucketName, Path.GetFileName(dlg.FileName), MimeUtility.GetMimeMapping(dlg.FileName), fileStream, uploadObjectOptions,progress: progressReporter).ConfigureAwait(true);
btn_getFiles_Click(sender, e);
}
}
}
// Called when progress updates
void OnUploadProgress(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case Google.Apis.Upload.UploadStatus.Starting:
progressBar1.Minimum = 0;
progressBar1.Value = 0;
break;
case Google.Apis.Upload.UploadStatus.Completed:
progressBar1.Value = progressBar1.Maximum;
break;
case Google.Apis.Upload.UploadStatus.Uploading:
UpdateProgressBar(progress.BytesSent);
break;
case Google.Apis.Upload.UploadStatus.Failed:
MessageBox.Show("Upload failed"
+ Environment.NewLine
+ progress.Exception);
break;
}
}
void UpdateProgressBar(long value)
{
progressBar1.BeginInvoke(new Action(()=> {
progressBar1.Value = (int)value;
}));
}
public string BytesToReadableValue(long number)
{
var suffixes = new List<string> { " B", " KB", " MB", " GB", " TB", " PB" };
for (int i = 0; i < suffixes.Count; i++)
{
long temp = number / (int)Math.Pow(1024, i + 1);
if (temp == 0)
{
return (number / (int)Math.Pow(1024, i)) + suffixes[i];
}
}
return number.ToString();
}
private void btn_getFiles_Click(object sender, EventArgs e)
{
var files = new List<fileInfo>();
foreach (var obj in storageClient.ListObjects(bucketName, ""))
{
var file = new fileInfo();
file.id = obj.Generation.ToString();
file.md5 = obj.Md5Hash;
file.name = obj.Name;
file.size = obj.Size + "";
file.sizeText = BytesToReadableValue(long.Parse(obj.Size.ToString()));
files.Add(file);
}
dataGridView1.DataSource = files;
lbl_file.DataBindings.Clear();
lbl_file.DataBindings.Add("text", files, "name");
lbl_byte.DataBindings.Clear();
lbl_byte.DataBindings.Add("text", files, "size");
}
private async void btn_download_Click(object sender, EventArgs e)
{
var dlg = new SaveFileDialog();
dlg.FileName = lbl_file.Text;
if (dlg.ShowDialog() == DialogResult.OK)
{
var token = new CancellationTokenSource().Token;
using (var fileStream = File.Create(dlg.FileName))
{
progressBar1.Maximum = int.Parse(lbl_byte.Text);
var downloadObjectOptions = new DownloadObjectOptions
{
ChunkSize = UploadObjectOptions.MinimumChunkSize
};
var progressReporter = new Progress<IDownloadProgress>(OnDownloadProgress);
await storageClient.DownloadObjectAsync(bucketName, Path.GetFileName(dlg.FileName), fileStream, downloadObjectOptions, token, progress: progressReporter).ConfigureAwait(true);
}
}
}
void OnDownloadProgress(IDownloadProgress progress)
{
switch (progress.Status)
{
case DownloadStatus.Completed:
progressBar1.Value = progressBar1.Maximum;
break;
case DownloadStatus.Downloading:
UpdateProgressBar(progress.BytesDownloaded);
break;
case DownloadStatus.Failed:
MessageBox.Show("Download failed"
+ Environment.NewLine
+ progress.Exception);
break;
}
}
private void btn_delete_Click(object sender, EventArgs e)
{
storageClient.DeleteObject(bucketName, lbl_file.Text);
btn_getFiles_Click(sender, e);
}
}
public class fileInfo
{
public string id { get; set; }
public string md5 { get; set; }
public string name { get; set; }
public string size { get; set; }
public string sizeText { get; set; }
}
}
Video Demo ứng dụng c#:
Các bạn có thể download source bên dưới về để tham khảo.
Thanks for watching!