I have a JSON file that I've added to the project's Resources/Raw/ folder and I have it marked as a MAUI Asset.
In the CSProj file I have:
<!-- Raw Assets (also remove the "Resources\Raw" prefix) -->
<MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
<ItemGroup>
<MauiAsset Update="Resources\Raw\ClientSecrets.json">
<LogicalName>ClientSecrets.json</LogicalName>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</MauiAsset>
</ItemGroup>
The code that I'm accessing the file with looks like this:
private GoogleCredential GetCredentialsFromFile()
{
GoogleCredential credential;
using(var stream = new FileStream($"ClientSecrets.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream).CreateScoped(Scopes);
}
return credential;
}
All of this works on iOS builds to virtual and physical devices, but the MacCatalyst build throws this error during runtime:
Could not find file '/Users/kurt/Projects/Dirt_Wain_Compost_Logger/Dirt_Wain_Compost_Logger/bin/Debug/net7.0-maccatalyst/maccatalyst-x64/Dirt_Wain_Compost_Logger.app/ClientSecrets.json'.
The build succeeds, the error is when I launch the program while debugging.
I have tried changing the filepath in the FileStream function to look for $"Contents/ClientSecrets.json" and it works for MacCataylst but then throws the same error for the iOS devices.
Does anyone know what I'm doing wrong? I feel like there has to be a way to make it work for all platforms without making exceptions.
Thanks!!
Whelp... it looks like I just didn't know about the .NET Maui Filesystem Helpers found here:
This did the trick
public async Task<GoogleCredential> ReadTextFile(string filePath)
{
using (Stream fileStream = await FileSystem.Current.OpenAppPackageFileAsync(filePath))
{
GoogleCredential credential;
credential = GoogleCredential.FromStream(fileStream).CreateScoped(Scopes);
return credential;
};
}
private GoogleCredential GetCredentialsFromFile()
{
GoogleCredential credential = ReadTextFile($"ClientSecrets.json").Result;
return credential;
}
The build is now working for iOS and Mac-Catalyst.