如何在 Google Drive 的 appfolder 中列出所有孩子并使用 Xamarin/c# 读取文件内容? [英] How to list all children in Google Drive's appfolder and read file contents with Xamarin / c#?

查看:28
本文介绍了如何在 Google Drive 的 appfolder 中列出所有孩子并使用 Xamarin/c# 读取文件内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试处理应用程序文件夹中的文本文件.

I'm trying to work with text files in the apps folder.

这是我的 GoogleApiClient 构造函数:

Here's my GoogleApiClient constructor:

googleApiClient = new GoogleApiClient.Builder(this)
   .AddApi(DriveClass.API)
   .AddScope(DriveClass.ScopeFile)
   .AddScope(DriveClass.ScopeAppfolder)
   .UseDefaultAccount()
   .AddConnectionCallbacks(this)
   .EnableAutoManage(this, this)
   .Build();

我正在联系:

googleApiClient.Connect()

之后:

OnConnected()

我需要列出 app 文件夹中的所有文件.这是我到目前为止所得到的:

I need to list all files inside the app folder. Here's what I got so far:

    IDriveFolder appFolder = DriveClass.DriveApi.GetAppFolder(googleApiClient);
    IDriveApiMetadataBufferResult result = await appFolder.ListChildrenAsync(googleApiClient);

这给了我文件元数据.

但在那之后,我不知道如何阅读、编辑或保存新文件.它们是使用我的应用的先前版本(本机)创建的文本文件.

But after that, I don't know how to read them, edit them or save new files. They are text files created with my app's previous version (native).

我正在关注驱动器的谷歌文档,但 Xamarin API 有很大不同,并且没有文档或示例.这是我正在使用的 API:https://components.xamarin.com/view/googleplayservices-开车

I'm following the google docs for drive but the Xamarin API is a lot different and has no docs or examples. Here's the API I'm using: https://components.xamarin.com/view/googleplayservices-drive

以下是从指南中读取文件内容的示例:

Here is an example to read file contents from the guide:

    DriveFile file = ...
    file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null)
        .setResultCallback(contentsOpenedCallback);

首先,我在指南中找不到DriveFile file = ..."是什么意思.我如何获得这个实例?DriveFile 似乎是这个 API 中的一个静态类.我试过了:

First I can't find anywhere in the guide what "DriveFile file = ..." means. How do I get this instance? DriveFile seems to be a static class in this API. I tried:

IDriveFile file = DriveClass.DriveApi.GetFile(googleApiClient, metadata.DriveId);

这有两个问题,首先它抱怨 GetFile 已被弃用,但没有说明如何正确执行.其次,该文件没有打开"方法.

This has two problems, first it complains that GetFile is deprecated but doesn't say how to do it properly. Second, the file doesn't have an "open" method.

感谢任何帮助.

推荐答案

Xamarin 绑定库包装了 Java Drive 库 (https://developers.google.com/drive/),因此如果您牢记 Binding 的 Java 到 C# 转换,则基于 Android 的 Drive API 的所有指南/示例都可以使用:

The Xamarin binding library wraps the Java Drive library (https://developers.google.com/drive/), so all the guides/examples for the Android-based Drive API work if you keep in mind the Binding's Java to C# transformations:

  • 获取/设置方法 -> 属性
  • 字段 -> 属性
  • 听众 -> 事件
  • 静态嵌套类 -> 嵌套类
  • 内部类 -> 带有实例构造函数的嵌套类

因此,当驱动器项目是文件夹时,您可以通过使用Metadata 递归地列出AppFolder 的目录和文件.

So you can list the AppFolder's directory and files by recursively using the Metadata when the drive item is a folder.

await Task.Run(() =>
{
    async void GetFolderMetaData(IDriveFolder folder, int depth)
    {
        var folderMetaData = await folder.ListChildrenAsync(_googleApiClient);
        foreach (var driveItem in folderMetaData.MetadataBuffer)
        {
            Log.Debug(TAG, $"{(driveItem.IsFolder ? "(D)" : "(F)")}:{"".PadLeft(depth, '.')}{driveItem.Title}");
            if (driveItem.IsFolder)
                GetFolderMetaData(driveItem.DriveId.AsDriveFolder(), depth + 1);
        }
    }
    GetFolderMetaData(DriveClass.DriveApi.GetAppFolder(_googleApiClient), 0);
});

输出:

[SushiHangover.FlightAvionics] (D):AppDataFolder
[SushiHangover.FlightAvionics] (F):.FlightInstrumentationData1.json
[SushiHangover.FlightAvionics] (F):.FlightInstrumentationData2.json
[SushiHangover.FlightAvionics] (F):.FlightInstrumentationData3.json
[SushiHangover.FlightAvionics] (F):AppConfiguration.json

编写(文本)文件示例:

using (var contentResults = await DriveClass.DriveApi.NewDriveContentsAsync(_googleApiClient))
using (var writer = new OutputStreamWriter(contentResults.DriveContents.OutputStream))
using (var changeSet = new MetadataChangeSet.Builder()
       .SetTitle("AppConfiguration.txt")
       .SetMimeType("text/plain")
       .Build())
{
    writer.Write("StackOverflow Rocks\n");
    writer.Write("StackOverflow Rocks\n");
    writer.Close();
    await DriveClass.DriveApi.GetAppFolder(_googleApiClient).CreateFileAsync(_googleApiClient, changeSet, contentResults.DriveContents);
}

注意:用 IDriveFolder 代替 DriveClass.DriveApi.GetAppFolder 以将文件保存在 AppFolder 的子文件夹中.

Note: Substitute a IDriveFolder for DriveClass.DriveApi.GetAppFolder to save a file in a subfolder of the AppFolder.

注意:以下示例中的 driveItem 是一个现有的基于 text/plain 的 MetaData 对象,它是通过遍历 Drive 内容找到的(请参阅获取目录/文件列表以上)或通过创建查询 (Query.Builder) 并通过 DriveClass.DriveApi.QueryAsync 执行它.

Note: driveItem in the following example is an existing text/plain-based MetaData object that is found by recursing through the Drive contents (see Get Directory/File list above) or via creating a query (Query.Builder) and executing it via DriveClass.DriveApi.QueryAsync.

var fileContexts = new StringBuilder();
using (var results = await driveItem.DriveId.AsDriveFile().OpenAsync(_googleApiClient, DriveFile.ModeReadOnly, null))
using (var inputStream = results.DriveContents.InputStream)
using (var streamReader = new StreamReader(inputStream))
{
    while (streamReader.Peek() >= 0)
        fileContexts.Append(await streamReader.ReadLineAsync());
}
Log.Debug(TAG, fileContexts.ToString());

这篇关于如何在 Google Drive 的 appfolder 中列出所有孩子并使用 Xamarin/c# 读取文件内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆