如何确定本地文件夹中是否存在文件(Windows.Storage.ApplicationData.Current.LocalFolder)在Windows Phone 8.1上?
很遗憾,目前没有直接的方法可以检查文件是否存在。您可以尝试使用以下两种方法之一:
一个简单的扩展方法可能看起来像这样:
public static class FileExtensions
{
public static async Task<bool> FileExists(this StorageFolder folder, string fileName)
{
try { StorageFile file = await folder.GetFileAsync(fileName); }
catch { return false; }
return true;
}
public static async Task<bool> FileExist2(this StorageFolder folder, string fileName)
{ return (await folder.GetFilesAsync()).Any(x => x.Name.Equals(fileName)); }
}
然后您可以像这样使用它们:
bool isFile = await ApplicationData.Current.LocalFolder.FileExists("myfile.txt");
如果文件不存在且文件夹中的文件较少,第二种方法可能会更快,因此不会抛出异常。