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

本文关键字:登录 NET 驱动器 读取 编辑文件 谷歌 | 更新日期: 2023-09-27 18:25:48

在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;

当谈到授权时,我想避免用户复制和粘贴返回的代码,我已经大量使用了谷歌示例助手,但必须有一个更简单的方法!

private static 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应用程序示例>吗?

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

真无聊!!

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

上面的代码是有效的——只怪它在凌晨3点编码。。。