【发布时间】:2022-09-14 17:59:31
【问题描述】:
这段代码让我摸不着头脑好几天了。
我正在尝试使用 Google Drive 和服务帐户为我的应用程序实现自动更新。
在我的 Google Drive 中有一个名为 Update 的文件夹,它与服务帐户共享。 在 Update 文件夹中有两个文件,一个名为 Version.txt 的文本文件,它是最新版本号的字符串,以及一个可执行文件 Update.exe,它是最新的应用程序版本。
我可以很好地读取 Version.txt 文件,但是当我尝试下载 ~1MB 可执行文件时,似乎在下载文件的过程中会出现延迟,但之后内存流 ms2 始终为空。
有人有想法么?这可能与服务帐户身份验证有关,但我不确定如何解决。
public class GoogleDriveAccess
{
//google drive file IDs
private readonly static string versionFileID = @"blahblahblahblah";
private readonly static string updateFileID = @"blehblehblehbleh";
//check for updated assembly on google drive and install if authorised
public async static void CheckForUpdate()
{
try
{
//load json key file from resources into a byte array
var jsonFile = Properties.Resources.drive_access;
//create service account keyfile from json byte array
var serviceAccountKeyfile = System.Text.Encoding.Default.GetString(jsonFile);
//create Google credentials with full access from service account keyfile
GoogleCredential credential = GoogleCredential.FromJson(serviceAccountKeyfile)
.CreateScoped(new[] { DriveService.ScopeConstants.Drive });
//create Google drive service using credentials
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
});
//get version file metadata
var getRequest = service.Files.Get(versionFileID);
//download version file to memory
await using var ms = new MemoryStream();
await getRequest.DownloadAsync(ms);
//read memory stream into a string
ms.Position = 0;
var sr = new StreamReader(ms);
string textUpdateVersion = sr.ReadToEnd().Trim();
//obtain our current assembly version
Version currentVersion = Assembly.GetEntryAssembly().GetName().Version;
//create an assembly version from the downloaded version text file
Version updateVersion = new Version(textUpdateVersion);
//if downloaded version is higher than our current version then request to download new assembly
if (updateVersion > currentVersion)
{
//prompt user to commence update
DialogResult result = MessageBox.Show($"Would you like to update to the latest version {updateVersion}?", Properties.Resources.AppName, MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
//get update file metadata
getRequest = service.Files.Get(updateFileID);
//download update file to memory
await using var ms2 = new MemoryStream();
await getRequest.DownloadAsync(ms2);
//***ms2 is always empty here***
//convert file to binary
ms2.Position = 0;
var br = new BinaryReader(ms2);
byte[] bin = br.ReadBytes(Convert.ToInt32(ms2.Length));
//rest of code
}
}
}
catch
{
//deal with any exceptions
}
}
}
【问题讨论】:
-
我会尝试其他一些文件类型。我认为您可能陷入了 .exe 文件不被认为是安全的,并且存在无法下载的陷阱。您是否尝试过从网络应用程序下载它?
-
这只是更改文件扩展名的问题吗?我最初上传的文件没有扩展名,但这也不起作用。
-
这是官方下载示例。 media_download 看看有没有帮助。
-
哦,我尝试从 Web 应用程序下载,它认为它感染了病毒,所以我需要使用我期望的
acknowledgeAbuse标志。
标签: c# winforms google-drive-api .net-6.0 google-api-dotnet-client