如何检查WinRT中的StorageFolder中是否存在文件

gur*_*gui 3 windows-8 windows-runtime

可能重复:
检查WinRT中项目中是否存在文件

我正在使用StorageFolder,需要检查文件是否存在,因为我读了它以避免异常.

我的代码看起来像这样:

StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await storageFolder.GetFileAsync(myPath);
Run Code Online (Sandbox Code Playgroud)

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

Iri*_*son 13

上次我检查你必须捕获异常:(可能已更改)

编辑:这是一种方法:)

像这样:

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

  • 我认为这种方式更好:var folder = ApplicationData.Current.LocalFolder; var file = await folder.TryGetItemAsync("file.txt")as IStorageFile; if(file!= null){//文件存在,"file"变量包含对它的引用.} else {//该文件不存在.} (7认同)