我正在使用 C# Google Drive V3 Api。我需要从垃圾箱中恢复一些文件。我能够以编程方式找到已删除的文件,但找不到任何
Untrash
或 Restore
或类似的方法。我能找到的与垃圾箱相关的唯一方法是EmptyTrash
,如下图所示。那我该如何恢复文件呢?
代码
public void Restore(DateTime from, DateTime to)
{
var driveService = DriveServiceFactory.Create();
foreach (var file in GetTrashedFiles(from, to))
{
var newFileMetadata = new GoogleDrive.Data.File { Id = file.Id, Trashed = false };
var updateReq = driveService.Files.Update(fnewFileMetadata, file.Id);
updateReq.AddParents = string.Join(",", file.Parents);
updateReq.Execute();
}
}
public static class DriveServiceFactory
{
public static DriveService Create()
{
UserCredential credential;
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
clientSecrets: GoogleClientSecrets.Load(stream).Secrets,
scopes: new[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile, DriveService.Scope.DriveMetadata },
user: "user",
taskCancellationToken: CancellationToken.None,
dataStore: new FileDataStore(credPath, true)
).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
var driveService = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyApp",
});
return driveService;
}
}
private IEnumerable<GoogleDrive.Data.File> GetTrashedFiles(DateTime @from, DateTime to)
{
var fileFieldsToQuery = "id, name, mimeType, size, createdTime, modifiedTime, md5Checksum, permissions(id, displayName, emailAddress, role), parents, trashed, trashedTime, trashingUser";
var listRequest = _driveService.Files.List();
listRequest.PageSize = 1000;
listRequest.Fields = $"nextPageToken, files({fileFieldsToQuery})";
listRequest.Q = "trashed=true";
var filesFeed = listRequest.Execute();
while (filesFeed.Files != null)
{
foreach (var file in filesFeed.Files)
{
if (file.Trashed.Value && @from <= file.ModifiedTime && file.ModifiedTime <= to)
yield return file;
}
// last page
if (filesFeed.NextPageToken == null)
{
break;
}
// prepare the next page of results
listRequest.PageToken = filesFeed.NextPageToken;
// get next page
filesFeed = listRequest.Execute();
}
}