2012-08-29 21 views
19

Pregunta similar a here. Solo para Google Drive en lugar de Dropbox:¿Cómo puedo localizar mediante programación mi carpeta de Google Drive con C#?

¿Cómo puedo localizar mediante programación mi carpeta Google Drive usando C#?

  • Registro?
  • Variable del entorno?
  • Etc ...
+0

Quiero permitir que el usuario seleccione "Google Drive" en lugar de C: \ Users \ XY \ Google Drive \ como carpeta principal durante la instalación de mi software. Busqué en el registro y en AppData. Hay un sync_config.db en% APPDATA% \ Local \ Google \ Drive, pero no sé cómo manejarlo. – wollnyst

+0

¿Has probado con la API de Google Drive? https://developers.google.com/drive/quickstart – Surfbutler

+0

¿Has echado un vistazo aquí ?: https://developers.google.com/drive/examples/dotnet – Ademar

Respuesta

14

yo personalmente creo, la mejor manera es tener acceso al mismo archivo a través SQLite3.

string dbFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Google\\Drive\\sync_config.db"); 
if (!File.Exists(dbFilePath)) 
    dbFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Google\\Drive\\user_default\\sync_config.db"); 

string csGdrive = @"Data Source="+ dbFilePath + ";Version=3;New=False;Compress=True;";     
SQLiteConnection con = new SQLiteConnection(csGdrive); 
con.Open(); 
SQLiteCommand sqLitecmd = new SQLiteCommand(con); 

//To retrieve the folder use the following command text 
sqLitecmd.CommandText = "select * from data where entry_key='local_sync_root_path'"; 

SQLiteDataReader reader = sqLitecmd.ExecuteReader(); 
reader.Read(); 
//String retrieved is in the format "\\?\<path>" that's why I have used Substring function to extract the path alone. 
Console.WriteLine("Google Drive Folder: " + reader["data_value"].ToString().Substring(4)); 
con.Dispose(); 

Usted puede obtener la biblioteca SQLite para .Net de here. También agregue referencia a System.Data.SQLite e inclúyalo en su proyecto para ejecutar el código anterior.

Para recuperar el usuario, relpace entry_key='user_email' en el código anterior

4

Tomé la respuesta de Sarath, reelaborado a ser más resistentes (comillas alrededor de la ruta de origen de datos, nula condicionales en la indexación de lector, la comprobación de errores adicional, "usar" para que los objetos se eliminen adecuadamente, se agreguen un montón de comentarios y se agreguen algunos LINQ (porque, linq :-)).

Esta implementación en particular detecta y registra excepciones, y luego devuelve la cadena. Vacío en cualquier error ... porque así es como lo necesita mi aplicación actual. Elimine el try/catch si su aplicación quiere excepciones.

/// <summary> 
/// Retrieves the local Google Drive directory, if any. 
/// </summary> 
/// <returns>Directory, or string.Empty if it can't be found</returns> 
public static string GetGoogleDriveDirectory() 
{ 
    try 
    { 
     // Google Drive's sync database can be in a couple different locations. Go find it. 
     string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); 
     string dbName = "sync_config.db"; 
     var pathsToTry = new[] { @"Google\Drive\" + dbName, @"Google\Drive\user_default\"+ dbName }; 

     string syncDbPath = (from p in pathsToTry 
          where File.Exists(Path.Combine(appDataPath, p)) 
          select Path.Combine(appDataPath, p)) 
          .FirstOrDefault(); 
     if (syncDbPath == null) 
      throw new FileNotFoundException("Cannot find Google Drive sync database", dbName); 

     // Build the connection and sql command 
     string conString = string.Format(@"Data Source='{0}';Version=3;New=False;Compress=True;", syncDbPath); 
     using (var con = new SQLiteConnection(conString)) 
     using (var cmd = new SQLiteCommand("select * from data where entry_key='local_sync_root_path'", con)) 
     { 
      // Open the connection and execute the command 
      con.Open(); 
      var reader = cmd.ExecuteReader(); 
      reader.Read(); 

      // Extract the data from the reader 
      string path = reader["data_value"]?.ToString(); 
      if (string.IsNullOrWhiteSpace(path)) 
       throw new InvalidDataException("Cannot read 'local_sync_root_path' from Google Drive configuration db"); 

      // By default, the path will be prefixed with "\\?\" (unless another app has explicitly changed it). 
      // \\?\ indicates to Win32 that the filename may be longer than MAX_PATH (see MSDN). 
      // Parts of .NET (e.g. the File class) don't handle this very well, so remove this prefix. 
      if (path.StartsWith(@"\\?\")) 
       path = path.Substring(@"\\?\".Length); 

      return path; 
     } 
    } 
    catch (Exception ex) 
    { 
     Trace.TraceError("Cannot determine Google Drive location. Error {0} - {1}", ex.Message, ex.StackTrace); 
     return string.Empty; 
    } 
} 
Cuestiones relacionadas