Vyhľadanie súborov na Google Drive podľa názvu, vrátane plnej cesty.
using System;
using System.Collections.Generic;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
class Program
{
static void Main()
{
string serviceAccountJsonPath = "service.json";
string? fileNameToSearch;
var cFG = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("Enter filename: ");
Console.ForegroundColor = ConsoleColor.White;
fileNameToSearch = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.Green;
var service = GetDriveService(serviceAccountJsonPath);
List<string> fileIds = FindFiles(service, fileNameToSearch);
Console.WriteLine("Files with the given name:");
foreach (var fileId in fileIds)
{
string filePath = GetFilePath(service, fileId);
if (filePath.Contains("Rubbish")) continue;
Console.WriteLine($"File ID: {fileId}, Full Path: /{filePath}");
}
Console.ForegroundColor = cFG;
}
// Create service
// ==============
static DriveService GetDriveService(string serviceAccountJsonPath)
{
var credential = GoogleCredential.FromFile(serviceAccountJsonPath)
.CreateScoped(DriveService.ScopeConstants.Drive);
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "YourAppName",
});
return service;
}
// FindFiles
// =========
static List<string> FindFiles(DriveService service, string? fileName)
{
List<string> fileIds = new List<string>();
// Define the query to search for files with a specific name
string query = $"name='{fileName}'";
// Request the files
var request = service.Files.List();
request.Q = query;
var result = request.Execute();
if (result.Files != null && result.Files.Count > 0)
{
foreach (var file in result.Files)
{
fileIds.Add(file.Id);
}
}
else
{
Console.WriteLine("No files found.");
}
return fileIds;
}
// GetFilePath
// ===========
static string GetFilePath(DriveService service, string fileId)
{
var request = service.Files.Get(fileId);
request.Fields = "id,name,parents";
var file = request.Execute();
string filePath = file.Name;
while (file.Parents != null && file.Parents.Count > 0)
{
var parentId = file.Parents[0];
var request1 = service.Files.Get(parentId);
request1.Fields = "id,name,parents";
file = request1.Execute();
filePath = $"{file.Name}/{filePath}";
}
return filePath;
}
}