22

ここと同様の質問。代わりGoogle DriveDropbox

Google DriveC#を使用してプログラムでフォルダーを見つけるにはどうすればよいですか?

  • レジストリ?
  • 環境変数?
  • 等...
4

2 に答える 2

18

個人的には、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();

ここから .Net 用の SQLite ライブラリを入手できます。また、参照を追加System.Data.SQLiteしてプロジェクトに含め、上記のコードを実行します。

ユーザーを取得するにはentry_key='user_email'、上記のコードから置き換えます

于 2012-11-09T15:14:24.793 に答える
5

Sarath の回答を参考にして、より回復力のあるものに作り直しました (データ ソース パスを引用符で囲み、リーダーのインデックス作成を条件とする null、追加のエラー チェック、オブジェクトを適切に破棄するための "使用"、たくさんのコメントを追加し、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;
    }
}
于 2016-06-30T18:08:43.940 に答える