如何检查windowsstore应用程序中是否存在文件

Mic*_*ren 5 c# windows-8 windows-store-apps

在Windows 8 app dev上创建实验室.我无法加载所需的所有图像.因此,为了共享部分使用共享图像,我需要检查图像文件是否可用.该项目是一个使用XAML和C#的Windows网格应用程序.过去我使用过

Using System.IO
 ... lost of code
privat void share()
....
    if (File.exist(filename)
    { 
       add file to share
    }
Run Code Online (Sandbox Code Playgroud)

如果我在我的window8项目中尝试这个.找不到File类.

我搜索互联网但无法找到一个代码示例来检查C#中windowsstore应用程序的存在

米希尔

May*_*ank 13

你需要StorageFileFile

这是检查和获取文件的简单示例

StorageFile file;
try {
    file = await ApplicationData.Current.LocalFolder.GetFileAsync("foo.txt");
}
catch (FileNotFoundException) {
    file = null;
}
Run Code Online (Sandbox Code Playgroud)

你可以写一个函数

public static async Task<bool> FileExistsAsync(this StorageFolder folder, string fileName)
{
    try
    {
        await folder.GetFileAsync(fileName);
        return true;
    }
    catch (FileNotFoundException)
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在Windows 8.1中,您可以使用新方法避免(慢速)异常处理:[TryGetItemAsync()](http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage. storagefolder.trygetitemasync.aspx). (2认同)