检查WinRT中的项目中是否存在文件

Pau*_*els 12 windows-8 windows-runtime windows-store-apps

我有一个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;
}
Run Code Online (Sandbox Code Playgroud)

示例调用:

GetMyImage("First Picture");
GetMyImage("Second Picture");
Run Code Online (Sandbox Code Playgroud)

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

起初我想过使用WinRT相当于File.Exists(),但似乎没有.无需尝试打开文件并捕获错误,我可以简单地检查文件是否存在,或者文件是否存在于项目中?

N_A*_*N_A 15

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

获取当前文件夹及其子文件夹中所有文件的列表.根据指定的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
}
Run Code Online (Sandbox Code Playgroud)

编辑:

正如@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
Run Code Online (Sandbox Code Playgroud)


小智 6

有两种方法可以处理它.

1)尝试获取文件时捕获FileNotFoundException:

 Windows.Storage.StorageFolder installedLocation = 
     Windows.ApplicationModel.Package.Current.InstalledLocation;
 try
 {
     // Don't forget to decorate your method or event with async when using await
     var file = await installedLocation.GetFileAsync(fileName);
     // Exception wasn't raised, therefore the file exists
     System.Diagnostics.Debug.WriteLine("We have the file!");
 }
 catch (System.IO.FileNotFoundException fileNotFoundEx)
 {
     System.Diagnostics.Debug.WriteLine("File doesn't exist. Use default.");
 }
 catch (Exception ex)
 {
     // Handle unknown error
 }
Run Code Online (Sandbox Code Playgroud)

2)正如mydogisbox建议的那样,使用LINQ.虽然我测试的方法略有不同:

 Windows.Storage.StorageFolder installedLocation =
     Windows.ApplicationModel.Package.Current.InstalledLocation;
 var files = await installedLocation.GetFilesAsync(CommonFileQuery.OrderByName);
 var file = files.FirstOrDefault(x => x.Name == fileName);
 if (file != null)
 {
    System.Diagnostics.Debug.WriteLine("We have the file!");
 }
 else
 {
    System.Diagnostics.Debug.WriteLine("No File. Use default.");
 }
Run Code Online (Sandbox Code Playgroud)