【问题标题】:Issue with using C# code with accessing Google Drive/Files using Service Account使用 C# 代码使用服务帐户访问 Google 云端硬盘/文件时出现问题
【发布时间】:2023-02-25 03:41:01
【问题描述】:

我正在使用 Visual Studio/Net MAUI for Windows/Android/IOS 开发一个应用程序,它需要自动访问 Google Drive 上的 mp3 文件并直接播放它们。

在网上查看后,我发现如果我使用 OAuth2,应用程序用户必须使用 Google 登录提示进行身份验证。我正在使用服务帐户。

我为实现上述目标而添加的代码出现错误。

根据我对如何进行 Google Drive 身份验证和从 Google Drive 检索文件目录/名称的理解,我添加了以下代码:

在 MauiProgram.c 中,我为包含服务帐户详细信息的 Json 文件添加了配置:

public static MauiApp CreateMauiApp()
{
    var assembly = Assembly.GetExecutingAssembly();
    using var FStream = assembly.GetManifestResourceStream("MyApp.apps.json");
    var config = new ConfigurationBuilder()
             .AddJsonStream(FStream)
             .Build();

以下代码位于单独的 ViewModel 中,用于文件访问:

    public async void PlayMP3Files()
    {
        var credential = GoogleCredential.FromStream(FStream);
        BaseClientService Service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "My App"
        });

        var folderName = "My Folder";
        var request = Service.Files.List();

        request.Q = $"mimeType='application/vnd.google-apps.folder' and name='{folderName}'";
        var result = await request.ExecuteAsync();
        string folder = result.Files.FirstOrDefault();
        if (folder != null)
        {
            var fileName = "My File";
            request = Service.Files.List();
            request.Q = $"mimeType!='application/vnd.google-apps.folder' and name='{fileName}'";
            result = await request.ExecuteAsync();
            string file = result.Files.FirstOrDefault();
            if (file != null)
            {
                // Play file
            }
        }
    }

构建上述内容时,它失败并出现以下错误:

  1. 严重性代码说明项目文件行抑制状态

    错误 CS0103 当前上下文中不存在名称“FStream”

  2. 严重性代码说明项目文件行抑制状态

    错误 CS1061“BaseClientService”不包含“Files”的定义,并且找不到接受“BaseClientService”类型的第一个参数的可访问扩展方法“Files”(是否缺少 using 指令或程序集引用?)

    我不确定如何将 FStream 链接到它在 Mauiprogram.c 中的用法。

    我想我已经包含了 BaseClientService 的指令/程序集参考。查看 Google.Apis.Services 背后的代码,似乎没有文件声明。

    解决上述问题的任何帮助将不胜感激。

    谢谢

【问题讨论】:

  • 您不需要包含 Severity Code Description Project File Line Suppression State - 任何 C# 开发人员都知道它们是什么。仅错误代码和消息通常就足够了

标签: c# google-drive-api maui


【解决方案1】:

using 块创建一个变量,该变量在块结束时立即超出范围。语句末尾的 ; 结束该块。在这种情况下,using 真的没有意义(我可以看到)

而是试试这个

var FStream = assembly.GetManifestResourceStream("MyApp.apps.json");
var config = new ConfigurationBuilder()
         .AddJsonStream(FStream)
         .Build();

【讨论】: