Store application-specific data

The application data folder is a special hidden folder that your app can use to store application-specific data, such as configuration files. The application data folder is automatically created when you attempt to create a file in it. Use this folder to store any files that the user shouldn't directly interact with. This folder is only accessible by your application and its contents are hidden from the user and from other Drive apps.

The application data folder is deleted when a user uninstalls your app from their MyDrive. Users can also delete your app's data folder manually.

Application data folder scope

Before you can access the application data folder, you must request access to the https://www.googleapis.com/auth/drive.appdata scope. For more information about scopes and how to request access to them, refer to Authenticate your users.

Create a file in the application data folder

To create a file in the application data folder, specify appDataFolder in the parents property of the file and use the files.create method to upload the file to the folder. The following example shows how to insert a file into a folder using a client library:

Java

File fileMetadata = new File();
fileMetadata.setName("config.json");
fileMetadata.setParents(Collections.singletonList("appDataFolder"));
java.io.File filePath = new java.io.File("files/config.json");
FileContent mediaContent = new FileContent("application/json", filePath);
File file = driveService.files().create(fileMetadata, mediaContent)
    .setFields("id")
    .execute();
System.out.println("File ID: " + file.getId());

Python

file_metadata = {
    'name': 'config.json',
    'parents': ['appDataFolder']
}
media = MediaFileUpload('files/config.json',
                        mimetype='application/json',
                        resumable=True)
file = drive_service.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()
print 'File ID: %s' % file.get('id')

Node.js

var fileMetadata = {
  'name': 'config.json',
  'parents': ['appDataFolder']
};
var media = {
  mimeType: 'application/json',
  body: fs.createReadStream('files/config.json')
};
drive.files.create({
  resource: fileMetadata,
  media: media,
  fields: 'id'
}, function (err, file) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    console.log('Folder Id:', file.id);
  }
});

.NET

drive/snippets/drive_v3/DriveV3Snippets/UploadAppData.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class of demonstrate the use of Drive upload app data. 
    public class UploadAppData
    {
        /// <summary>
        /// Insert a file in the application data folder and prints file Id.
        /// </summary>
        /// <param name="filePath">File path to upload.</param>
        /// <returns>ID's of the inserted files, null otherwise.</returns>
        public static string DriveUploadAppData(string filePath)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });
                var fileMetadata = new Google.Apis.Drive.v3.Data.File()
                {
                    Name = "config.json",
                    Parents = new List<string>()
                    {
                        "appDataFolder"
                    }
                };
                FilesResource.CreateMediaUpload request;
                using (var stream = new FileStream(filePath,
                           FileMode.Open))
                {
                    request = service.Files.Create(
                        fileMetadata, stream, "application/json");
                    request.Fields = "id";
                    request.Upload();
                }

                var file = request.ResponseBody;
                // Prints the file id.
                Console.WriteLine("File ID: " + file.Id);
                return file.Id;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

For further information on creating files in folders, refer to Create and populate folders.

Search for files in the application data folder

To search for files in ithe application data folder, set the spaces field to appDataFolder and use the files.list method. The following example shows how to search for files in the application data folder using a client library:

Java

FileList files = driveService.files().list()
    .setSpaces("appDataFolder")
    .setFields("nextPageToken, files(id, name)")
    .setPageSize(10)
    .execute();
for (File file : files.getFiles()) {
  System.out.printf("Found file: %s (%s)\n",
      file.getName(), file.getId());
}

Python

response = drive_service.files().list(spaces='appDataFolder',
                                      fields='nextPageToken, files(id, name)',
                                      pageSize=10).execute()
for file in response.get('files', []):
    # Process change
    print 'Found file: %s (%s)' % (file.get('name'), file.get('id'))

Node.js

drive.files.list({
  spaces: 'appDataFolder',
  fields: 'nextPageToken, files(id, name)',
  pageSize: 100
}, function (err, res) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    res.files.forEach(function (file) {
      console.log('Found file:', file.name, file.id);
    });
  }
});

.NET

drive/snippets/drive_v3/DriveV3Snippets/ListAppData.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate use-case of Drive's list files in the application data folder.
    public class ListAppData
    {
        /// <summary>
        /// List down files in the application data folder.
        /// </summary>
        /// <returns>list of 10 files, null otherwise.</returns>
        public static FileList DriveListAppData()
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                var request = service.Files.List();
                request.Spaces = "appDataFolder";
                request.Fields = "nextPageToken, files(id, name)";
                request.PageSize = 10;
                var result = request.Execute();
                foreach (var file in result.Files)
                {
                    // Prints the list of 10 file names.
                    Console.WriteLine("Found file: {0} ({1})", file.Name, file.Id);
                }
                return result;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}