【发布时间】:2015-02-13 03:38:51
【问题描述】:
如何判断文件是否存在于本地文件夹 (Windows.Storage.ApplicationData.Current.LocalFolder) 在 Windows Phone 8.1 上?
【问题讨论】:
如何判断文件是否存在于本地文件夹 (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");
如果文件不存在并且文件夹中的文件很少,则第二种方法可能会快一点,因此不会引发异常。
【讨论】: