来自同一作者,有一篇关于如何将文件上传/下载到 Google Drive 的文档。
与大多数 Google API 一样,您需要通过身份验证才能连接到它们。为此,您必须首先在 Google Developer Console 上注册您的应用程序。在 API 下一定要启用 Google Drive API 和 Google Drive SDK,一如既往不要忘记在同意屏幕表单上添加产品名称和电子邮件地址。
确保您的项目至少设置为 .net 4.0。
添加以下NuGet包
PM> Install-Package Google.Apis.Drive.v2
为了download 一个文件,我们需要知道它的文件资源,获取文件ID 的唯一方法是通过我们之前使用的Files.List() 命令。
public static Boolean downloadFile(DriveService _service, File _fileResource, string _saveTo)
{
if (!String.IsNullOrEmpty(_fileResource.DownloadUrl))
{
try
{
var x = _service.HttpClient.GetByteArrayAsync(_fileResource.DownloadUrl );
byte[] arrBytes = x.Result;
System.IO.File.WriteAllBytes(_saveTo, arrBytes);
return true;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return false;
}
}
else
{
// The file doesn't have any content stored on Drive.
return false;
}
}
使用_service.HttpClient.GetByteArrayAsync,我们可以将我们想要下载的文件的下载地址传递给它。下载文件后,只需将文件写入磁盘即可。
请记住,在创建目录以 upload 文件时,您必须能够告诉 Google 它的 mime-type 是什么。我在这里有一个小方法可以尝试解决这个问题。只需将文件名发送给它。注意:将文件上传到 Google Drive 时,如果文件名与已存在的文件同名。谷歌云端硬盘只是上传它,那里的文件没有更新,你最终会得到两个同名的文件。它仅基于fileId 而非基于文件名进行检查。如果你想更新一个文件,你需要使用更新命令,我们稍后会检查。
public static File uploadFile(DriveService _service, string _uploadFile, string _parent) {
if (System.IO.File.Exists(_uploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(_uploadFile);
body.Description = "File uploaded by Diamto Drive Sample";
body.MimeType = GetMimeType(_uploadFile);
body.Parents = new List() { new ParentReference() { Id = _parent } };
// File's content.
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
request.Upload();
return request.ResponseBody;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else {
Console.WriteLine("File does not exist: " + _uploadFile);
return null;
}
}