无法使用c#

时间:2018-01-07 23:21:21

标签: c# google-api google-drive-api google-oauth

我正在使用google api v2并尝试将一些文件上传到我的goodle硬盘。 但不幸的是,我遇到了一些困难。我可以轻松读取所有文件 开车但不能推进去。 这是我用来上传文件的代码:

    public static  File UploadFile (DriveService service, string uploadFile,
        string description , string parent)
    {
        if (System.IO.File.Exists(uploadFile))
        {
            File body = new File();
            body.Title = System.IO.Path.GetFileName(uploadFile);
            body.Description = description;
            body.MimeType = GetMimeType(uploadFile);
            body.Parents = new List<ParentReference>() { new 
                               ParentReference() { Id = "root" } };

            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.UploadAsync();
                return request.ResponseBody;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Error Occured");
                return null;                 
            }
        }
        else
        {
            MessageBox.Show("The file does not exist.", "404");
            return null;
        }

    }

    private static string GetMimeType(string fileName)
    {
        string mimeType = "application/unknown";
        string ext = System.IO.Path.GetExtension(fileName).ToLower();
        Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
        if (regKey != null && regKey.GetValue("Content Type") != null)
            mimeType = regKey.GetValue("Content Type").ToString();
        return mimeType;
    }

此处用于启动文件上传的代码:

static string[] Scopes = { DriveService.Scope.Drive, DriveService.Scope.DriveFile };
static string ApplicationName = "myprojname";
var clientId = @"MyID";
var clientSecret = @"MySecret";

var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
                {
                    ClientId = clientId,
                     ClientSecret = clientSecret
                },
                Scopes,
                Environment.UserName,
                CancellationToken.None,
                new FileDataStore("MyAppsToken")).Result;

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

var res = GoogleDriveHelper.UploadFile(service, @"pathtofile.txt", "desc", null);

在所有动作请求结果(request.ResponseBody)为空之后,我变瘦了 权限中的一些问题。但我没有t deny them login to gmail account. And I don知道错误在哪里或我错过了什么。 谢谢你的帮助

0 个答案:

没有答案