3

I am in the process of migrating a regular .net framework legacy library into a .net standard library. As shown in the picture below, the legacy library used to have a file that is always copied to the Output folder:

enter image description here

In that library, there is a legacy class that test the existence of the folder before accessing the file on the disk, like this:

namespace Library
{
    public class LegacyClass
    {
        public void AccessFile()
        {
            string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            bool directoryExists = Directory.Exists(Path.Combine(path, "Files"));

            //  It does exist in the Console app. It does not in the Android app.
            // ... And then access the file.
        }
    }
}

While it was working with a Console app, it is not working in a blank Xamarin application:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.activity_main);

    //  
    var legacyClass = new LegacyClass();

    legacyClass.AccessFile();
}

The LegacyClass is not able to find the Files folder:

enter image description here

Question

How can a Xamarin.Android application access files that have the Copy to Output Directory set to CopyAlways?

Kzryzstof
  • 7,688
  • 10
  • 61
  • 108
  • You can check the native android code of a xamarin.forms files access library https://www.c-sharpcorner.com/article/local-file-storage-using-xamarin-form/ – Nick Kovalsky Aug 17 '18 at 13:22

1 Answers1

0

You can't do that, but you can achieve your goal using embedded resources easily.

https://developer.xamarin.com/samples/mobile/EmbeddedResources/

Instead, you've to add file to your csproj, then you can set its build action to Embedded Resource in the properties of that file. (Select file in solution explorer and press F4).

At runtime, you can use the following that returns a Stream to your file:

Assembly.Load("MyProjectWhichContainsTheFile").GetManifestResourceStream("MyFile.txt")

Kzryzstof
  • 7,688
  • 10
  • 61
  • 108
Yaser Moradi
  • 3,267
  • 3
  • 24
  • 50
  • 2
    you might have to prefix your filename with the default namespace: GetManifestResourceStream is used to access the embedded file using its Resource ID. By default the resource ID is the filename prefixed with the default namespace for the project it is embedded in - in this case the assembly is WorkingWithFiles and the filename is LibTextResource.txt, so the resource ID is WorkingWithFiles.LibTextResource.txt. [Loading Files Embedded as Resources](https://learn.microsoft.com/de-de/xamarin/xamarin-forms/data-cloud/data/files?tabs=windows) – Tilmann Bach Feb 22 '20 at 15:03