2012-08-29 1 views
19

here과 비슷한 질문입니다. Google Drive 대신 Dropbox :C#을 사용하여 프로그래밍 방식으로 Google 드라이브 폴더를 찾으려면 어떻게해야하나요?

어떻게 프로그래밍 방식으로 C#을 사용하여 Google Drive 폴더를 찾을 수 있습니까?

  • 레지스트리?
  • 환경 변수?
  • 기타 ...
+0

내 소프트웨어를 설치하는 동안 사용자가 부모 폴더로 C : \ Users \ XY \ Google 드라이브 대신 "Google 드라이브"를 선택하도록 허용하려고합니다. 나는 레지스트리와 AppData를 검색했다. % APPDATA % \ Local \ Google \ Drive에 sync_config.db가 있지만 이것을 처리하는 방법을 모르겠습니다. – wollnyst

+0

Google 드라이브 API를 사용해 보셨습니까? https://developers.google.com/drive/quickstart – Surfbutler

+0

여기를 보셨습니까? https://developers.google.com/drive/examples/dotnet – Ademar

답변

14

개인적으로 생각하는 가장 좋은 방법은 sqlite3를 통해 같은 파일에 액세스하는 것입니다.

닷넷 용 SQLite 라이브러리는 here에서 가져올 수 있습니다. 또한 System.Data.SQLite에 대한 참조를 추가하고 위 코드를 실행하려면 프로젝트에 포함 시키십시오.

위의 코드

4

내가 Sarath의 답변을했다 (탄력으로이를 재 작업에서 사용자, relpace entry_key='user_email'를 검색하려면 독자 색인에 널 (null) 조건 데이터 소스 경로, 따옴표, 추가 오류 검사, "using"그래서 적절하게 처리되고, 많은 주석을 추가하고, 일부 LINQ를 던집니다 (linq :-) 때문에).

이 특정 구현은 예외를 캐치하고 로그에 기록한 다음 오류가 발생하면 string.Empty를 반환합니다. 현재 응용 프로그램이이를 필요로하기 때문입니다. 앱이 예외를 원할 경우 try/catch를 제거하십시오.

/// <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; 
    } 
} 
관련 문제