Search code examples
macosxamarin.formspathios-simulatorvisual-studio-mac

Problem with building paths iOS v MacOs in Xamarin Forms app


I have this code:

var myDocuments = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "..", "Shared");
_rootPath = Path.Combine(myDocuments, "VisitsRota.MacOS");
_stylesPath = Path.Combine(_rootPath, "Styles");
_vrrDataFile = Path.Combine(_rootPath, "VisitsRotaData.xml");

// Read in the required data
vrrData = DeserializeFromXml<VisitsRotaData>(_vrrDataFile);

// Build list of month names. Should this property also have a private counterpart?
ListMonths = DateTimeFormatInfo.CurrentInfo.MonthNames.TakeWhile(m => m != String.Empty).ToList();

// Select the current month in the list
ListMonthsSelectedItem = DateTime.Now.ToString("MMMM");

string[] stylesArray = Directory.GetFiles(_stylesPath, "ElderlyInfirm-Schedule-*.xsl")
                          .Select(file => Path.GetFileName(file)).ToArray<string>();

On the Mac it runs as expect. But on the iOS simulator (which I am new to using) it raises an exception:

enter image description here

System.IO.DirectoryNotFoundException: Could not find a part of the path '/Users/xxxxxxx/Library/Developer/CoreSimulator/Devices/B812608B-8131-4386-B189-C646684A8965/data/Containers/Data/Application/EF23B73D-8D38-4F41-995E-FCAE13AE3035/Shared/VisitsRota.MacOS/Styles'.

How should I be able to replicate testing on my iOS build? if I use literal paths instead of Path.Combine etc. I do not have a problem.


Solution

  • I was able to resolve this. My related question / answer about resources helped.

    In the comments to this question I was asked:

    How are these files being deployed with your app?

    That was the key!

    I added a constructor to the AppDelegate class:

    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        public AppDelegate()
        {
            InstallApplicationFiles();
        }
    

    The linked Q & A has more info. By getting the app to copy the default files from the resources the issue of paths with the iOS simulator is resolved.