在Xamarin.Forms中,如何从项目的文件夹中读取资产列表? [英] In Xamarin.Forms, how to read a list of assets from a project's folder?

查看:44
本文介绍了在Xamarin.Forms中,如何从项目的文件夹中读取资产列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个可以重现某些音轨的应用程序.这些音轨位于目录"Music"中,我无法假定它们是固定的,因此无法使用文件名一一读取它们.

I am trying to do an app that reproduce some audio tracks. The tracks are inside a directory "Music" and I cannot asume they are fixed, hence I cannot read them 1 by 1 using the file's name.

解决方案目录树:

MySolution/

  MyApp/
    Music/
      track01
      track02
      ...
    App.xaml
    MyAppPage.xaml   

  MyApp.Droid/
    ...   

  MyApp.iOS/
    ...

我需要实现的是这样的:

What I need to achieve is something like this:

MyAppPage.xaml.cs

namespace MyNamespace
{
    public partial class MyAppPage : ContentPage
    {
        public MyAppPage()
        {
            InitializeComponent();

            var files = Directory.GetFiles("./Music");
            musicListView.ItemsSource = files;
        }
    }
}

MyAppPage.xaml

<?xml version="1.0" encoding="utf-8"?>
<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:MyNamespace"
    x:Class="MyNamespace.MyAppPage">

    <ContentPage.Content>

        <ListView x:Name="musicListView" />

    </ContentPage.Content>

</ContentPage>

我也尝试过:

var currentDir = Directory.GetCurrentDirectory();
var files = Directory.GetFiles(Path.Combine(currentDir, "Music"));

但是当前目录只是"/".我不知道我是否只是在弄乱路径,或者Xamarin是否不允许这种操作.如果是这样,是否有任何标准方法可以做到这一点?

But current dir is just "/". I don't know if I am simply messing with the paths or if Xamarin does not allow this kind of operations. If that's the case, is there any standard approach to do this?

推荐答案

嗯,wonna会得到一个列表吗?

Mmm wonna get a list?

    var assembly = typeof(App).GetTypeInfo().Assembly;
    var MyAssemblyName = assembly.GetName().Name; //now this is for the future
    //if you want acces files by a generated name would be:
    // MyAssemblyName + ".Music."+filename
    //anyway now we are building the whole list:
    var MusicFiles = new List<string>(); //todo change to your music class 
    foreach (var res in assembly.GetManifestResourceNames())
    {
        if (res.Contains(".track"))
        {
            MusicFiles.Add(res);
        }
    }

请不要忘记将文件包含为嵌入式资源"(请检查文件属性).

Do not forget to include files as Embedded Resource (check files properties).

此处的更多信息: https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/files/

这篇关于在Xamarin.Forms中,如何从项目的文件夹中读取资产列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆