How to use asset folder in class

Shay Wilner 1,746 Reputation points
2024-06-16T18:52:24.7533333+00:00

Hello

in android app xamarin project

I try to use the asset.open method in class A but Asset is not recognized

class ClassA
    {
        private List<string> listsunrisetlvastro = new List<string>();
        private void readfile()
        {
            string filecontent;
            Stream thestream = Assets.Open("sunrisetlvastro.txt");
            StreamReader reader = new StreamReader(thestream);
            filecontent = reader.ReadToEnd();
         }
    }


the name Assets doesn't exit .It works only in the Main activity

Thanks

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,325 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 71,836 Reputation points Microsoft Vendor
    2024-06-17T01:30:11.63+00:00

    Hello,

    You can create a static property and set it in the MainActivity.cs

    public class MainActivity : AppCompatActivity
    {
    
    //Create this static property
         public static MainActivity Instance { get; private set; }
    
         protected override void OnCreate(Bundle savedInstanceState)
         {
    //Set this property
             Instance = this;
    
             base.OnCreate(savedInstanceState);
             Xamarin.Essentials.Platform.Init(this, savedInstanceState);
     
             // Set our view from the "main" layout resource
             SetContentView(Resource.Layout.activity_main);
         }
    
    

    After that, you can use it in the ClassA.cs

    class ClassA
      {
          private List<string> listsunrisetlvastro = new List<string>();
          private void readfile()
          {
              string filecontent;
    
    //use this Instance value at here.
              Stream thestream = MainActivity.Instance.Assets.Open("sunrisetlvastro.txt");
    
              StreamReader reader = new StreamReader(thestream);
              filecontent = reader.ReadToEnd();
          }
      }
    

    As note: please make sure the buildAction of sunrisetlvastro.txt is AndroidAsset.

    In addition, Xamarin support ended on May 1, 2024 for all Xamarin SDKs including Xamarin.Forms. For more information, please check: Xamarin official support policy | .NET (microsoft.com). We will recommend you upgrade Xamarin.Android projects to . NET , please see the Upgrade from Xamarin to .NET & .NET MAUI documentation.

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful