简体   繁体   English

如何从XAML应用程序中的相对URI获取所有文件列表?

[英]How to get all files list from a relative URI in XAML application?

How to get all files from a folder in XAML application using relative path? 如何使用相对路径从XAML应用程序中的文件夹中获取所有文件?

I am playing with a Kinect application built in WPF. 我正在玩一个内置在WPF中的Kinect应用程序。 All images used in the application are in [project dir]\\Images\\ and all backgrounds are in [project dir]\\Images\\Backgrounds\\ . 应用程序中使用的所有图像都在[project dir]\\Images\\ ,所有背景都在[project dir]\\Images\\Backgrounds\\

I want to get list of all the images from Backgrounds directory using relative path. 我想使用相对路径从Backgrounds目录中获取所有图像的列表。 I have tried 我努力了

DirectoryInfo(@"\Images\Backgrounds\").GetFiles();

but it says that Backgrounds directory must exist in [full path+project dir]\\debug\\bin\\ 但它说背景目录必须存在于[full path+project dir]\\debug\\bin\\

Selecting each image manually works fine 手动选择每个图像工作正常

Uri uri = new Uri(@"Images\Backgrounds\Background1.png", UriKind.Relative);
ImageSource imgsource = new BitmapImage(uri);
this.Backdrop.Source = imgsource;

It works for a single file because you specify URI to resource embedded in the assembly and not some folder on your drive, whilst GetFiles() will work only on a specific physical folder. 它适用于单个文件,因为您指定了嵌入在程序集中的资源的URI而不是驱动器上的某个文件夹,而GetFiles()仅适用于特定的物理文件夹。 So either you need to copy all your images instead of embedding them or use the code below and resourceNames should give you names of all resources that you can reference by URI in your project: 因此,您需要复制所有图像而不是嵌入它们或使用下面的代码, resourceNames应该为您提供项目中URI可以引用的所有资源的名称:

List<string> resourceNames = new List<string>();
var assembly = Assembly.GetExecutingAssembly();
var rm = new ResourceManager(assembly.GetName().Name + ".g", assembly);
try
{
    var list = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true);
    foreach (DictionaryEntry item in list)
        resourceNames.Add((string)item.Key);
}
finally
{
    rm.ReleaseAllResources();
}

if you need then at this point each item.Value contains UnmanagedMemoryStream for each resource. 如果你需要,那么每个item.Value包含每个资源的UnmanagedMemoryStream

I would reply to your post instead of posting a solution, but I'm new to this site and dont have that privledge yet.... Hey! 我会回复你的帖子,而不是发布一个解决方案,但我是这个网站的新手,还没有那个权利......嘿! Just trying to help. 只是想帮忙。

Anyway, I've had a problem similar to this before concerning DirectoryInfo. 无论如何,我之前遇到过与DirectoryInfo类似的问题。 Can't remember exactly how I solved it, but I remember the backslashes being tricky. 不记得我是怎么解决它的,但我记得反斜杠很棘手。 Have you checked out the MSDN site? 你检查过MSDN网站了吗? It seems like it can't find your directory so its looking for it in debug by default. 它似乎无法找到您的目录,因此它默认在调试中查找它。 MSDN says the format should be "MyDir\\MySubdir" in C#. MSDN说格式应该是C#中的“MyDir \\ MySubdir”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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