【问题标题】:How to check if file exists in StorageFolder in WinRT [duplicate]如何检查WinRT中的StorageFolder中是否存在文件[重复]
【发布时间】:2013-01-13 04:20:36
【问题描述】:

可能重复:
Check if a file exists in the project in WinRT

我正在使用 StorageFolder,需要在读取文件之前检查文件是否存在以避免异常。

我的代码如下所示:

StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await storageFolder.GetFileAsync(myPath);

问题是,我找不到检查文件是否存在的方法

【问题讨论】:

    标签: windows-8 windows-runtime


    【解决方案1】:

    上次我检查您是否必须捕获异常: (可能已经改变)

    编辑:这是一种方法:)

    像这样:

        static async Task<bool> DoesFileExistAsync(string fileName)
        {
            try
            {
                await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
                return true;
            }
            catch
            {
                return false;
            }
        }
    

    【讨论】:

    • 我觉得这样比较好:var folder = ApplicationData.Current.LocalFolder; var file = await folder.TryGetItemAsync("file.txt") as IStorageFile; if (file != null) { // 文件存在,“file”变量包含对它的引用。 } else { // 文件不存在。 }
    • Jon,TryGetItemAsync 仅适用于 Windows 8.1,不适用于 Windows Phone 8.1。您的回答有效,但不适用于通用应用。
    • 这是否尝试读取所有文件数据?还是只获取元数据?
    猜你喜欢
    • 2021-08-09
    • 1970-01-01
    • 2012-01-25
    • 2019-08-05
    • 1970-01-01
    • 2015-11-06
    • 2011-05-19
    • 2011-10-04
    相关资源
    最近更新 更多