How can I load the contents of a local file into a byte array?

garrwillgarrwill Member ✭✭

I hope "local file" is even the correct term. I want to load the contents of a file in Resources/drawable in an Android app into a byte array. How?
And should it have a Build Action other than AndroidResource?

Best Answer

  • garrwillgarrwill ✭✭
    Accepted Answer

    I managed to get Xamarin.Essentials installed and working.

    Oddly, I had to change the first line in the sample code above to the following:

    Stream s = Xamarin.Essentials.FileSystem.OpenAppPackageFileAsync("myfilename").Result;

    Other than that, your answer resolved my issue. Thanks.

Answers

  • PaulNTUPaulNTU USMember ✭✭✭

    You could use the assets folder for this and set the build action to AndroidAsset. If you use Xamarin essentials it makes it really easy to get the file contents

    Stream s = await Xamarin.Essentials.FileSystem.OpenAppPackageFileAsync(filename);
    byte[] data;
    
    using (MemoryStream ms = new MemoryStream())
    {
        s.CopyTo(ms);
        data= ms.ToArray();
        ms.Dispose();
    }
    
  • garrwillgarrwill Member ✭✭

    Sounds promising. Next question: How do I get Xamarin Essentials?

  • garrwillgarrwill Member ✭✭
    Accepted Answer

    I managed to get Xamarin.Essentials installed and working.

    Oddly, I had to change the first line in the sample code above to the following:

    Stream s = Xamarin.Essentials.FileSystem.OpenAppPackageFileAsync("myfilename").Result;

    Other than that, your answer resolved my issue. Thanks.

Sign In or Register to comment.