加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

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

发布时间:2020-12-13 20:06:58 所属栏目:Windows 来源:网络整理
导读:我有一个WinRT Metro项目,它根据所选项目显示图像.但是,某些选定的图像将不存在.我想要做的是陷阱他们不存在的情况,并显示一个替代方案. 这是我的代码到目前为止 internal string GetMyImage(string imageDescription){ string myImage = string.Format("Ass
我有一个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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读