3

在 c# 中,我想读取和写入谷歌驱动器上的文件,我看到大多数示例应用程序使用控制台来收集从登录尝试返回的参数。我想在 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;

当涉及到授权时,我想避免用户复制和粘贴返回的代码,我大量使用了谷歌示例帮助程序,但必须有更简单的方法!

私有静态 IAuthorizationState GetAuthorization(NativeApplicationClient 客户端){

        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 example的例子>?

4

1 回答 1

0

多么愚蠢!

字符串范围 = " https://www.googleapis.com/auth/drive ";

上面的代码有效 - 只需将其归咎于凌晨 3 点的编码......

于 2013-08-02T11:52:10.810 回答