You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI应用使用服务账号访问Google Drive文件报错求助

问题解决步骤

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

MauiProgram.cs中的FStream是局部变量,ViewModel无法直接访问,可通过以下两种方式解决:

方式1:ViewModel直接读取嵌入式资源

服务账号JSON作为嵌入式资源,ViewModel可自行读取,无需依赖外部变量:

// 在ViewModel的PlayMP3Files方法中添加
var assembly = Assembly.GetExecutingAssembly();
using var fStream = assembly.GetManifestResourceStream("MyApp.apps.json");
var credential = GoogleCredential.FromStream(fStream)
    .CreateScoped(DriveService.Scope.DriveReadonly); // 根据需求添加权限范围

方式2:依赖注入传递凭证

在MauiProgram中初始化Google凭证并注册服务,ViewModel通过构造函数注入使用:

// MauiProgram.cs
public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>()
        .ConfigureFonts(fonts =>
        {
            fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
        });

    // 初始化Google凭证
    var assembly = Assembly.GetExecutingAssembly();
    using var fStream = assembly.GetManifestResourceStream("MyApp.apps.json");
    var credential = GoogleCredential.FromStream(fStream)
        .CreateScoped(DriveService.Scope.DriveReadonly);

    // 注册DriveService单例
    builder.Services.AddSingleton<DriveService>(sp => new DriveService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "My App"
    }));

    // 注册你的ViewModel
    builder.Services.AddTransient<YourViewModel>();

    return builder.Build();
}

ViewModel通过构造函数接收DriveService:

public class YourViewModel
{
    private readonly DriveService _driveService;

    public YourViewModel(DriveService driveService)
    {
        _driveService = driveService;
    }

    // PlayMP3Files方法直接使用_driveService即可
}

错误2:CS1061(“BaseClientService”不包含“Files”的定义)

该错误由两个原因导致,逐一修复:

  1. 修正类型声明:BaseClientService是抽象基类,无Files属性,需使用具体的DriveService类型:
// 替换原BaseClientService声明
DriveService service = new DriveService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "My App"
});
  1. 安装必要NuGet包:仅引用Google.Apis.Services不足,需安装Google.Apis.Drive.v3包,Files属于Drive v3 API的核心成员。

隐性错误修正

代码中result.Files.FirstOrDefault()返回的是Google.Apis.Drive.v3.Data.File对象,而非string,需修正变量类型:

// 错误写法
string folder = result.Files.FirstOrDefault();
// 正确写法
var targetFolder = result.Files.FirstOrDefault();

修改后的完整ViewModel代码(方式1示例)

using System.Reflection;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;

public async void PlayMP3Files()
{
    try
    {
        var assembly = Assembly.GetExecutingAssembly();
        using var fStream = assembly.GetManifestResourceStream("MyApp.apps.json");
        if (fStream == null) return;

        var credential = GoogleCredential.FromStream(fStream)
            .CreateScoped(DriveService.Scope.DriveReadonly);

        DriveService service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "My App"
        });

        // 查询目标文件夹
        var folderRequest = service.Files.List();
        folderRequest.Q = $"mimeType='application/vnd.google-apps.folder' and name='My Folder'";
        var folderResult = await folderRequest.ExecuteAsync();
        var targetFolder = folderResult.Files.FirstOrDefault();

        if (targetFolder != null)
        {
            // 查询文件夹内的MP3文件(添加父文件夹ID条件避免全局搜索)
            var fileRequest = service.Files.List();
            fileRequest.Q = $"mimeType='audio/mpeg' and name='My File' and '{targetFolder.Id}' in parents";
            var fileResult = await fileRequest.ExecuteAsync();
            var targetFile = fileResult.Files.FirstOrDefault();

            if (targetFile != null)
            {
                // 获取MP3下载链接,使用MAUI的MediaElement或AudioPlayer播放
                var downloadUrl = targetFile.WebContentLink;
                // 示例:mediaElement.Source = new Uri(downloadUrl); mediaElement.Play();
            }
        }
    }
    catch (Exception ex)
    {
        // 处理异常逻辑
    }
}

内容的提问来源于stack exchange,提问作者AS468

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 01:58:15