加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

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

发布时间:2020-12-14 03:54:22 所属栏目:Windows 来源:网络整理
导读:我当前的方法是获取当前文件夹中的顶级文件,然后检查文件是否具有指定的文件名: public async Taskbool FileExists(StorageFolder folder,string fileName){ IReadOnlyListStorageFile fileList = await folder.GetFilesAsync(); StorageFile existFile = f
我当前的方法是获取当前文件夹中的顶级文件,然后检查文件是否具有指定的文件名:

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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读