简体   繁体   中英

how to access files in xamarin.android. And also in Visual Studio Solution explorer where should i place the file in order to locate it in my code

The code below tries to access file named zimbabwe in Asset folder

var fileContent = File.ReadAllText("Asset/zimbabwe.shp")

下图显示了用于尝试访问文件的代码以及放置文件的文件夹

How should I access files in xamarin.android? And also in Visual Studio Solution explorer where should I place the file in order to locate it in my code?

In Xamarin.Android project, Assets are read using an AssetManager . An instance of the AssetManager is available by accessing the Assets property on an Android.Content.Context , such as an Activity.

For example:

string content;
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader (assets.Open ("zimbabwe.shp")))
{
    content = sr.ReadToEnd ();
}

And in Xamarin.Forms project,you could also add any file into the Assets folder in the Android project and mark the Build Action as AndroidAsset to use it with OpenAppPackageFileAsync .

using (var stream = await FileSystem.OpenAppPackageFileAsync(templateFileName))
{
  using (var reader = new StreamReader(stream))
  {
    var fileContents = await reader.ReadToEndAsync();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM