This is an edit of my original question.
I have a C# .Net MAUI App that checks for the existence of a source file (the standard Project/Resources/Raw/AboutAssets.txt
file) during the OnAppearing()
event.
My question is why does this File.Exists
test not work on either Windows or Android?
My Code
using System.Diagnostics;
namespace SourceFileExists2;
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
Debug.WriteLine($"APP DATA DIRECTORY = {FileSystem.Current.AppDataDirectory}");
string sourceFile = "AboutAssets.txt";
Debug.WriteLine($"SOURCE FILE = {sourceFile}");
Debug.WriteLine($"FILE EXISTS 1 = {File.Exists(System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, sourceFile))}");
string sourcePath = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, sourceFile);
Debug.WriteLine($"SOURCE PATH = {sourcePath}");
Debug.WriteLine($"FILE EXISTS 2 = {File.Exists(sourcePath)}");
}
}
Windows Output
APP DATA DIRECTORY = C:\Users\Jason\AppData\Local\Packages\fd35e565-25c7-4731-bfd1-6267e4eafe80_9zz4h110yvjzm\LocalState
SOURCE FILE = AboutAssets.txt
FILE EXISTS 1 = False
SOURCE PATH = C:\Users\Jason\AppData\Local\Packages\fd35e565-25c7-4731-bfd1-6267e4eafe80_9zz4h110yvjzm\LocalState\AboutAssets.txt
FILE EXISTS 2 = False
Android Output
[0:] APP DATA DIRECTORY = /data/user/0/com.companyname.sourcefileexists2/files
[0:] SOURCE FILE = AboutAssets.txt
[0:] FILE EXISTS 1 = False
[0:] SOURCE PATH = /data/user/0/com.companyname.sourcefileexists2/files/AboutAssets.txt
[0:] FILE EXISTS 2 = False
Why does the file existence test not work on either Windows or Android?
As per documentation, System.IO.File.Exists()
takes an argument path
:
The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see
GetCurrentDirectory
.
If you would run from the code method System.IO.File.GetCurrentDirectory
, it will point possible to different directory than the result of FileSystem.Current.AppDataDirectory
(which you are using for saving).
To resolve this, you must combine and check the correct path:
string sourceFile = "AboutAssets.txt";
string sourcePath = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, sourceFile);
if (File.Exists(sourcePath))
{
// ...
}
The main takeaway is that there are 2 directories in MAUI approach:
Directory with application (with *.exe)
System.IO.File.GetCurrentDirectory
AppDomain.CurrentDomain.BaseDirectory
AppContext.BaseDirectory
C:\MyApp\myApp.exe
Directory with data per platform
FileSystem.Current.AppDataDirectory
(MAUI helper path)Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
(native)C:\Users\MyUser\AppData\Local\Packages\e1db9eee-54c8-48a0-8472-d7fda39ef4ed_9zz4h110yvjzm\LocalState