Windows-8 – 检查WinRT中项目中是否存在文件

我有一个WinRT Metro项目,它根据所选项目显示图像.但是,某些选定的图像将不存在.我想要做的是陷阱他们不存在的情况,并显示一个替代方案.

这是我的代码到目前为止

internal string GetMyImage(string imageDescription)
{
    string myImage = string.Format("Assets/MyImages/{0}.jpg",imageDescription.Replace(" ",""));

    // Need to check here if the above asset actually exists

    return myImage;
}

示例调用

GetMyImage("First Picture");
GetMyImage("Second Picture");

所以Assets / MyImages / SecondPicture.jpg存在,但Assets / MyImages / FirstPicture.jpg没有.

起初我想到使用WinRT相当于File.Exists(),但似乎不是一个.无需去尝试打开文件并捕获错误的程度,只需检查文件是否存在,或文件是否存在于项目中?

您可以使用 here中的GetFilesAsync枚举现有文件.考虑到您有多个可能不存在的文件,这似乎是有意义的.

Gets a list of all files in the current folder and its sub-folders. Files are filtered and sorted based on the specified CommonFileQuery.

var folder = await StorageFolder.GetFolderFromPathAsync("Assets/MyImages/");
var files = await folder.GetFilesAsync(CommonFileQuery.OrderByName);
var file = files.FirstOrDefault(x => x.Name == "fileName");
if (file != null)
{
    //do stuff
}

编辑:

正如@Filip Skakun指出的那样,资源管理器有一个资源映射,您可以在其上调用ContainsKey,它还有权检查合格资源(即本地化,缩放等).

编辑2:

Windows 8.1引入了一种新的获取文件文件夹的方法

var result = await ApplicationData.Current.LocalFolder.TryGetItemAsync("fileName") as IStorageFile;
if (result != null)
    //file exists
else
    //file doesn't exist

相关文章

Windows2012R2备用域控搭建 前置操作 域控主域控的主dns:自...
主域控角色迁移和夺取(转载) 转载自:http://yupeizhi.blo...
Windows2012R2 NTP时间同步 Windows2012R2里没有了internet时...
Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...