我正在开发 C# Windows 应用程序,用于将文件上传到 Google Drive。我需要确定已上传到 Google 云端硬盘的文件,以防出现任何故障。
我想避免出现文件开始上传但互联网关闭并且仅上传部分文件的情况。
如何比较文件传输到 Google 云端硬盘时没有出现任何问题。
下面是我用来将文件上传到 Google 云端硬盘的代码。
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<ParentReference>() { 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();
Google.Apis.Drive.v2.Data.File file = request.ResponseBody;
Google.Apis.Drive.v2.Data.Permission newPermission = new Google.Apis.Drive.v2.Data.Permission();
newPermission.Value = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="08393a3b486f65696164266b6765" rel="noreferrer noopener nofollow">[email protected]</a>";
newPermission.Type = "anyone";
newPermission.Role = "writer";
_service.Permissions.Insert(newPermission, file.Id).Execute();
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;
}
}
最佳答案
您可以注册 ProgressChanged
事件并检查 UploadStatus
属性以确认上传成功。
request.ProgressChanged += UploadProgessEvent;
和
private void UploadProgessEvent(Google.Apis.Upload.IUploadProgress obj)
{
if (obj.Status == Google.Apis.Upload.UploadStatus.Completed)
{
//Succesfully Uploaded
}
}
IUploadProgress
中还有一个 BytesSent
属性,您可以将其与原始文件大小进行比较以检查上传完成情况。
但是,正如 KENdi 引用的答案中提到的,来自insert
Documentation ,
If successful, this method returns a Files resource in the response body.
如果上传因任何原因失败,则抛出异常,并且 catch
block 必须处理它。
关于c# - 确保文件上传到 Google Drive C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42513668/