问题描述
我正在尝试制作一个重现一些音轨的应用程序.曲目位于音乐"目录中,我无法假设它们是固定的,因此我无法使用文件名一一读取它们.
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?
推荐答案
嗯,想要一份清单吗?
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 中,如何从项目文件夹中读取资产列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!