简体   繁体   中英

How to change permissions of a file on Google Drive to share it with anyone with link as viewer?

I tried many things but I can't get it working:

Permission permission = new Permission ( );
permission.Role = "reader";
permission.Type = "anyone";
permission.Id = "anyoneWithLink";

service.Permissions.Delete ( file.Id, file.PermissionIds [ 0 ] ).Execute();
service.Permissions.Update ( permission, file.Id, permission.Id ).Execute ( );

I see 2 permissions for some files, one with an Id set to "anyoneWithLink" but not sure if it's what I set as a user in Google Drive website. Because any other file that I didn't touch in the Google Drive website, their permissions are still owner, default, not anyoneWithLink.

How can I set the permissions for a file properly so the changes go through?

Credentials code:

        // If modifying these scopes, delete your previously saved credentials
    // at ~/.credentials/drive-dotnet-quickstart.json
    static string [ ] Scopes = { DriveService.Scope.DriveReadonly };
    static string ApplicationName = "Drive API .NET Quickstart";

    static void Main ( string [ ] args )
    {
        UserCredential credential;

        using ( var stream =
            new FileStream ( "credentials.json", FileMode.Open, FileAccess.Read ) )
        {
            // The file token.json stores the user's access and refresh tokens, and is created
            // automatically when the authorization flow completes for the first time.
            string credPath = "token.json";
            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,
        } );

After you delete a permission, you cannot update it - you need to create a new one.

  • When creating a new permission (also when updating one) - do not supply a permissionId in the request body
  • Instead, just provide as resource
Permission permission = new Permission ( );
permission.Role = "reader";
permission.Type = "anyone";
  • Setting permission.Type to anyone is enough for the file to become accessible by anyoneWithLink .

Note:

After setting the permissions correctly, from the UI it will look like this:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM