测试文件夹的完整路径存在而不依赖异常

Test full path to folder exists without relying on exception

我正在开发 C++ UWP/WinRT 应用程序, 并想测试一个给定的字符串是否代表一个现存文件夹的路径,我想在不依赖捕获异常的情况下完成它。动机在底部。

查看 UWP Storage API,似乎沿着这些路线的唯一不使用异常来传达成功的例程是 TryGetItemAsync(),不幸的是需要有一个 StorageFolder in-手,我看到从完整路径字符串中获取 StorageFolder 的唯一方法是通过 GetFolderFromPathAsync(),它使用异常来传达失败。

动机:一时兴起。即使被捕获,异常也会记录在输出中,并使其看起来像是失败了,这会减慢开发速度。也许我需要用更积极的方式来捕捉它。


编辑以包含将常用 C++ 代码与 UWP 进行比较的示例:

void cppTestFolder(const std::wstring path)
{
    bool existsCpp = !!(std::ifstream(path));
    bool existsUwp = UWP_Based_TestFolder(path);

    LogW(std::wstring(L"folder path exists ?  CPP: ") + (existsCpp ? L"yes" : L"no ") + L"  UWP: " + (existsUwp ? L"yes" : L"no ") + L"   path: " + path);
}

...
    cppTestFolder(L"C:\Data");
    cppTestFolder(L"C:\Data\no_such_folder");
...

and logging output: (minus the annoying exception messages I want to avoid)

folder path exists ?  CPP: no  UWP: yes  path: C:\Data
folder path exists ?  CPP: no  UWP: no   path: C:\Data\no_such_folder

Test full path to folder exists without relying on exception

恐怕你不依赖异常就无法检查文件夹是否存在。你可以参考document。建议使用异常检查文件夹的方法。正如你上面提到的 TryGetItemAsync 不是静态方法,所以它需要一个基本文件夹实例。

对于这种情况,检查文件夹路径的唯一方法是使用桌面桥。并处理桌面扩展中的文件夹检查并将结果发送回 UWP 客户端。桌面扩展没有这样的限制,你可以使用 File.Exists api 来检查存储项目。对于桌面桥,您可以参考 stefan' bolg UWP with Desktop Extension.