我正在开发一个控制台应用程序来管理Google驱动器上的文件,我的代码基于google.drive.api.v3文档。
我可以成功上传,下载和删除文件,但是我无法更新文件。
我正在使用UpdateMediaUpload
类中的以下方法:
public void Upload(UserCredential Credential, string folderGoogleId, string fileName, byte[] b)
{
using (DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = Credential,
ApplicationName = ApplicationName,
}))
{
try
{
var fileUp = new File();
fileUp.Name = fileName;
fileUp.MimeType = fileName.GetContentType();
fileUp.Parents = parent;
using (Stream stream = new MemoryStream(b))
{
FilesResource.UpdateMediaUpload request = service.Files.Update(fileUp, folderGoogleId, stream,fileUp.MimeType);
request.Upload();
var update = request.ResponseBody; // this is the value I want
}
}
catch (Exception e)
{
var msg = e.ToString();
}
}
}
但是当我使用此功能时,变量update
的值设置为null
,并且它不会更新文件。
如果有人知道如何解决此问题,我将非常有帮助。
[确定,这是一个解决方案,所有内容都不可读,异常显示不能在更新请求中直接写入主字段。改用addParents和removeParents参数。因此我将文件的父级移到了请求中
public void Upload(UserCredential Credential, string folderGoogleId, string fileName, byte[] b)
{
using (DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = Credential,
ApplicationName = ApplicationName,
}))
{
try
{
var fileUp = new File();
fileUp.Name = fileName;
fileUp.MimeType = fileName.GetContentType();
using (Stream stream = new MemoryStream(b))
{
FilesResource.UpdateMediaUpload request = service.Files.Update(fileUp, folderGoogleId, stream,fileUp.MimeType);
request.AddParents = folderGoogleId;
request.Upload();
var update = request.ResponseBody; // this is the value I want
}
}
catch (Exception e)
{
var msg = e.ToString();
}
}
}