在 WinRT 中检查项目中是否存在文件 [英] Check if a file exists in the project in WinRT

查看:22
本文介绍了在 WinRT 中检查项目中是否存在文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WinRT Metro 项目,它根据所选项目显示图像.但是,某些选定的图像将不存在.我希望能够做的是捕获它们不存在的情况并显示替代方案.

I have a WinRT Metro project which displays images based on a selected item. However, some of the images selected will not exist. What I want to be able to do is trap the case where they don't exist and display an alternative.

这是我目前的代码:

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 不存在.

So Assets/MyImages/SecondPicture.jpg exists, but Assets/MyImages/FirstPicture.jpg does not.

起初我想使用 File.Exists() 的 WinRT 等价物,但似乎没有.不必去尝试打开文件并捕获错误的程度,我可以简单地检查文件是否存在,或者文件是否存在于项目中?

At first I thought of using the WinRT equivalent of File.Exists(), but there doesn't appear to be one. Without having to go to the extent of trying to open the file and catching an error, can I simply check if either the file exists, or the file exists in the project?

推荐答案

您可以使用 此处 枚举现有文件.考虑到您有多个可能不存在的文件,这似乎是有道理的.

You could use GetFilesAsync from here to enumerate the existing files. This seems to make sense considering you have multiple files which might not exist.

获取当前文件夹及其子文件夹中所有文件的列表.文件根据指定的 CommonFileQuery 进行过滤和排序.

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,这也具有检查合格资源(即本地化、缩放等)的好处.

As @Filip Skakun pointed out, the resource manager has a resource mapping on which you can call ContainsKey which has the benefit of checking for qualified resources as well (i.e. localized, scaled etc).

编辑 2:

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

Windows 8.1 introduced a new method for getting files and folders:

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

这篇关于在 WinRT 中检查项目中是否存在文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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