windows-phone-8.1 – 如何知道指定的路径是否引用现有文件?

我当前的方法获取当前文件夹中的顶级文件,然后检查文件是否具有指定的文件名:

public async Task<bool> FileExists(StorageFolder folder,string fileName)
{
    IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync();
    StorageFile existFile = fileList.First(x => x.Name == fileName);
    return (existFile != null);
}

有没有简单有效的方法来做到这一点?

解决方法

对于Windows Phone 8.1 RT,我建议您使用try..catch,并且不要将抛出的异常等同于布尔值,因为此时不知道该文件是否存在.

bool IsFileKNownToExist = false;

bool IsFileKNownToNotExist = false;

string FileName = "?";

try 
{
    await folder.GetFileAsync(FileName);

    IsFileKNownToExist = true;

} 
catch(Exception ex)
{
    //handle exception and set the booleans here. 
}

一旦我能掌握一系列例外,我将重新审视这一点,然后将有一个改进的方式来等同于真或假.

但是,应该返回第三个结果,表示不知道文件是否存在.在这种情况下,值得设置一个枚举:

public static enum Success
{
    True,False,Unsure
}

然后您可以使用以下代码

Success IsFileKNownToExist = Success.Unsure;

string FileName = "?";

try 
{
    await folder.GetFileAsync(FileName);

    IsFileKNownToExist = Success.True;

} 
catch(Exception ex)
{
    //handle exception and set the booleans here. 
}

switch(IsFileKNownToExist)
{
    case Success.True:
        //Code here when file exists
        break;

    case Success.False:
        //Code here when file does not exist
        break;

    default:
    case Success.Unsure:
        //Code here when it isn't kNown whether file exists or not
        break;
}

相关文章

Windows2012R2备用域控搭建 前置操作 域控主域控的主dns:自...
主域控角色迁移和夺取(转载) 转载自:http://yupeizhi.blo...
Windows2012R2 NTP时间同步 Windows2012R2里没有了internet时...
Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...