谷歌驱动器读取和编辑文件并自动登录.NET

时间:2013-08-01 18:12:01

标签: c# winforms google-drive-api

在c#中我想读取和写入google驱动器上的文件,我看到大多数示例应用程序使用控制台来收集从登录尝试返回的args。我想在winforms应用程序中执行此操作。

        String CLIENT_ID = "XXXX";
        String CLIENT_SECRET = "XXXX";

        // Register the authenticator and create the service
        var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
        var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
        var service = new DriveService(new BaseClientService.Initializer()
        {
            Authenticator = auth
        });

        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;

说到授权,我想避免用户复制和粘贴回来的代码,我大量使用谷歌样本助手,但必须有一个更简单的方法!

private static IAuthorizationState GetAuthorization(NativeApplicationClient client)         {

        const string STORAGE = "XXXX";
        const string KEY = "XXXX";
        string scope = "";

        // Check if there is a cached refresh token available.
        IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY);
        if (state != null)
        {
            try
            {
                client.RefreshToken(state);
                return state; // Yes - we are done.
            }
            catch (DotNetOpenAuth.Messaging.ProtocolException ex)
            {
                //CommandLine.WriteError("Using existing refresh token failed: " + ex.Message);
            }
        }

        // Retrieve the authorization from the user.
        state = AuthorizationMgr.RequestNativeAuthorization(client, scope);
        AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state);
        return state;
    }

我需要做些什么才能让这个工作?什么是“范围”意味着设置为?

我读了无数文章,它似乎并不容易,有没有人有一个例子winforms app示例&gt;?

1 个答案:

答案 0 :(得分:0)

多么糟糕!!

string scope =“https://www.googleapis.com/auth/drive”;

以上代码有效 - 只是责备它在凌晨3点编码......