如何仅将文件夹上传到Google云端硬盘

时间:2014-07-09 14:38:02

标签: c# google-drive-api

tl; dr:无法将空文件夹上传到Google云端硬盘。 Google API尚不清楚,需要帮助。

我正在尝试创建一个可以将空文件夹上传到Google云端硬盘的程序。我查看了Google云端硬盘API处理文件夹的问题并不清楚,所以如果你们能给出更明确的答案,我们将不胜感激!

我尝试从Google切换源代码以上传文件,即 body.mimeType =“application / vnd.google-apps.folder”;等等。我得到的错误是UnauthorizedAccessException,因为你不能只将文件夹转换为byteArray。

我对C#知之甚少,所以我不知道如何解决这个问题。如果你也可以包含代码片段,以便我可以想象放置代码的位置,我也会很感激!

代码:

  Google.Apis.Drive.v2.Data.File folder = new Google.Apis.Drive.v2.Data.File();
        folder.Title = My Folder;
        folder.Description = desc.;
        folder.MimeType = applicationvnd.google-apps.folder;
       //Tried ^ that, didn't work

        FilesResource.InsertMediaUpload request = service.Files.Insert(folder).Fetch();
        Google.Apis.Drive.v2.Data.File file = service.Files.Insert(folder).Fetch();
        File file = service.Files.Insert(folder).Fetch();
       //Again, tried those but that didn't work either

        File body = new File();
        body.Title = "Document";
        body.Description = "A test folder";
        body.MimeType = "application/vnd.google-apps.folder";

        byte[] byteArray = System.IO.File.ReadAllBytes("Folder");
        //I know this doesn't work but had to try anyways
        System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

        FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "application/vnd.google-apps.folder");
        request.Upload();

        File file = request.ResponseBody;
        Console.WriteLine(File id  + file.Id);

我认为这是我尝试过的大部分内容,但都不起作用。还有其他我尝试但我已经删除了代码,因为它不起作用,重新找到它是没有意义的。

谢谢!

1 个答案:

答案 0 :(得分:2)

我解决了它(通过在另一个问题上找到答案):

而不是File file = service.Files.Insert(body).fetch(); (很多人说这不起作用,),使用File file = service.Files.Insert(body)。执行(); Upvote(或者这个论坛有效)答案在这里: Create folder on Google Drive .NET

代码:

File body = new File();
        body.Title = "document title";
        body.Description = "document description";
        body.MimeType = "application/vnd.google-apps.folder";

        // service is an authorized Drive API service instance
        File file = service.Files.Insert(body).Execute();

        //File body = new File();
        //body.Title = "My document";
        //body.Description = "A test document";
        //body.MimeType = "text/plain";

        //byte[] byteArray = System.IO.File.ReadAllBytes("document.txt");
        //System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

        //FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
        //request.Upload();

        //File file = request.ResponseBody;

我放入了我评论过的所有内容,因为我发现查看代码是什么并且没有包含它可以帮助它工作。此前源代码中的所有内容(请参阅Google上的快速入门C#以供参考)完全相同。

希望这可以帮助其他遇到同样问题的人!