How to create folder in Google Drive using .NET AP

2019-02-17 19:16发布

I am using C#, Google .NET API. How can I create a folder in Google Drive root location? Any code will be helpful. Thanks

3条回答
不美不萌又怎样
2楼-- · 2019-02-17 19:34
//First you will need a DriveService:

ClientSecrets cs = new ClientSecrets();
cs.ClientId = yourClientId;
cs.ClientSecret = yourClientSecret;

credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        cs,
                        new[] { DriveService.Scope.Drive },
                        "user",
                        CancellationToken.None,
                        null
                    ).Result;

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

//then you can upload the file:

File body = new File();
body.Title = "document title";
body.Description = "document description";
body.MimeType = "application/vnd.google-apps.folder";

File folder = service.Files.Insert(body).Execute();
查看更多
可以哭但决不认输i
3楼-- · 2019-02-17 19:35

In Google Drive API, a folder is nothing but a file with Mime Type: application/vnd.google-apps.folder

In API v2, you can use:

    // DriveService _service: Valid, authenticated Drive service
    // string_ title: Title of the folder
    // string _description: Description of the folder
    // _parent: ID of the parent directory to which the folder should be created

public static File createDirectory(DriveService _service, string _title, string _description, string _parent)
{
    File NewDirectory = null;

    File body = new File();
    body.Title = _title;
    body.Description = _description;
    body.MimeType = "application/vnd.google-apps.folder";
    body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };
    try
    {
        FilesResource.InsertRequest request = _service.Files.Insert(body);
        NewDirectory = request.Execute();
    }
    catch(Exception e)
    {
        MessageBox.Show(e.Message, "Error Occured");
    }
    return NewDirectory;
}  

For creating folder at the root directory, you may pass "root" as the parent ID.

查看更多
该账号已被封号
4楼-- · 2019-02-17 19:37

A folder can be treated as a file with a special MIME type: "application/vnd.google-apps.folder".

The following C# code should be what you need:

File body = new File();
body.Title = "document title";
body.Description = "document description";
body.MimeType = "application/vnd.google-apps.folder";

// service is an authorized Drive API service instance
File file = service.Files.Insert(body).Fetch();

For more details check the docs: https://developers.google.com/drive/folder

查看更多
登录 后发表回答