2

我已经阅读了一些问题,我尝试了这些示例,它们对我有用,这里是链接: -链接 1 -链接 2 -链接 3

但是,我试图完成的有点不同,我试图修改/上传一个包含纯文本的 .DAT 文件。我能够毫无问题地读取文件内容,但我总是收到 400 错误请求(协议错误)。这是我的代码。

   DocumentsService service = new DocumentsService("Man");
   service.setUserCredentials(UserName, Passwod);

   DocumentsListQuery fileQuery = new DocumentsListQuery();
   fileQuery.Query = User.FileName;
   fileQuery.TitleExact = true;
   DocumentsFeed feed = service.Query(fileQuery);

   //Here I get my file to update
   DocumentEntry entry = (DocumentEntry)feed.Entries[0];

    // Set the media source
  //Here I have tried application/octet-stream also
  entry.MediaSource = new MediaFileSource(DataStream, User.FileName, text/plain");

  // Instantiate the ResumableUploader component.
     ResumableUploader uploader = new ResumableUploader();

  // Set the handlers for the completion and progress events
  uploader.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(OnDone);
  uploader.AsyncOperationProgress += new syncOperationProgressEventHandler(OnProgress);

 ClientLoginAuthenticator authenticator = new ClientLoginAuthenticator("Man", ServiceNames.Documents,Credentials);
 Uri updateUploadUrl = new Uri(UploadUrl);
 AtomLink aLink = new AtomLink(updateUploadUrl.AbsoluteUri);
 aLink.Rel = ResumableUploader.CreateMediaRelation;
 entry.Links.Add(aLink);

// Start the update process.
uploader.UpdateAsync(authenticator,entry,new object());

谢谢。

编辑:这就是我解决它的方法。感谢克劳迪奥指导我正确的方向


  1. 下载示例应用程序:下载示例 (.zip)
  2. 从 SampleHelper Project 将这些实施到您的项目中:AuthorizationMgr、INativeAuthorizationFlow、LoopbackServerAuthorizationFlow、WindowTitleNativeAuthorizationFlow
  3. 将其与以下代码一起使用:

    //Call Authorization method... (omitted)
    
    File body = new File();
    body.Title = title;
    body.Description = description;
    body.MimeType = mimeType;
    byte[] byteArray = System.IO.File.ReadAllBytes(filename);
    MemoryStream stream = new MemoryStream(byteArray);
    
    try {
      FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
      request.Upload();
    
      File file = request.ResponseBody;
    
      // Uncomment the following line to print the File ID.
      // Console.WriteLine("File ID: " + file.Id);
    
      return file;
    } catch (Exception e) {
      Console.WriteLine("An error occurred: " + e.Message);
      return null;
    }
    
4

1 回答 1

2

每当服务器返回 400 Bad Request 时,它还包含一条描述性错误消息,告诉您请求中的无效内容。如果你不能从调试器中得到它,你应该安装 Fiddler 并捕获 HTTP 请求和响应。

我给你的另一个建议是开始使用更新的 Drive API 而不是 Documents List API。这是一个 5 分钟的 C# 快速入门示例,展示了如何将文件上传到 Google Drive:

https://developers.google.com/drive/quickstart

于 2012-08-31T22:19:36.037 回答