无法上传到Google云端硬盘

时间:2015-12-02 16:33:21

标签: c# .net google-drive-api

我正在尝试将JSON文件上传到任何人的GDrive中的根文件夹。我在尝试自行修复时,通过Google搜索了所有答案。无论我做了什么request.Responsebody总是返回null。在这里,我尝试做一个空白的.txt文件(它仍然无法正常工作)。

这是获取凭据的代码,然后将生成的DeviceService设置为变量。

//GDrive Cred
public static void GetCred()
{
    //Get Credential
    UserCredential credential;

    using (var stream =
        new FileStream(Path + "\\client_secret.json", FileMode.Open, FileAccess.Read))
    {
        string credPath = System.Environment.GetFolderPath(
            System.Environment.SpecialFolder.Personal);
        credPath = System.IO.Path.Combine(credPath, ".credentials/drive-dotnet-quickstart");

        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore(credPath, true)).Result;
        Console.WriteLine("Credential file saved to: " + credPath);
    }

    // Create Drive API service.
    var service = new DriveService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });

    mService = service;
}

这是上传文件的代码。

//Save JSON to GDrive
public static void SaveJSONtoDrive()
{

    GetCred();
    // File's metadata.
    Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
    body.Title = "ATGEntries.txt";
    body.Description = "Database JSON for Adventurer's Tour Guide";
    //body.MimeType = "application/json";
    body.MimeType = "text/plain";
    body.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } };

    // File's content.
    byte[] byteArray = System.IO.File.ReadAllBytes(Path + "\\ATGEntries.txt");
    MemoryStream stream = new MemoryStream(byteArray);
    try
    {
        FilesResource.InsertMediaUpload request = mService.Files.Insert(body, stream, "text/plain");
        request.UploadAsync();

        Google.Apis.Drive.v2.Data.File file = request.ResponseBody;

        // Uncomment the following line to print the File ID.
        Console.WriteLine("File ID: " + file.Id);
    }
    catch (Exception e)
    {
        Console.WriteLine("An error occurred: " + e.Message);

    }
}

有人可以尝试帮助我解决这个奇怪的错误吗?

1 个答案:

答案 0 :(得分:0)

我无法相信这不是任何地方所以我会回答我自己的问题,希望它能帮助其他人。

注意设置'credPath'变量的行

credPath = System.IO.Path.Combine(credPath, ".credentials/drive-dotnet-quickstart");

确保“.credentials /”之后的部分与您在Google Developers Console中为OAuth 2.0客户端ID命名的部分名称相同。这应该可以解决问题。