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:
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:
Question
How can a Xamarin.Android
application access files that have the Copy to Output Directory
set to CopyAlways
?
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")