【UWP】不通过异常判断文件是否存在

从WP升到WinRT(Win8/WP8.1/UWP)后所有的文件操作都变成StorageFile和StorageFolder的方式,但是微软并没有提供判断文件是否存在的方法通常的做法我们可以通过下面方式判断文件是否存在

 

1、通过FileNotFoundException异常判断

public async Task<bool> isFilePresent(string fileName)
{
    bool fileExists = true;
    Stream fileStream = null;
    StorageFile file = null;

    try
    {
        file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
        fileStream = await file.OpenStreamForReadAsync();
        fileStream.Dispose();
    }
    catch (FileNotFoundException)
    {
        // If the file dosn't exits it throws an exception, make fileExists false in this case 
        fileExists = false;
    }
    finally
    {
        if (fileStream != null)
        {
            fileStream.Dispose();
        }
    }

    return fileExists;
}

  由于异常的抛出对性能的开销非常大,我们也可以通过遍历文件名的方式判断文件是否存在

2、通过遍历文件

public async Task<bool> isFilePresent(string fileName)
{ 
    bool fileExists = false;
    var allfiles = await ApplicationData.Current.LocalFolder.GetFilesAsync();
    foreach (var storageFile in allfiles)
    {
        if (storageFile.Name == fileName)
        {
            fileExists = true;
        }
    }
    return fileExists;
}

  遍历显然是一种取巧的方式,如果文件多的画可能会影响性能

3、通过TryGetItemAsync方法获取(Win8/WP8.1不支持)

public async Task<bool> isFilePresent(string fileName)
{
    var item = await ApplicationData.Current.LocalFolder.TryGetItemAsync(fileName);
    return item != null;
}

 

推荐使用第三种方式更快一些,第一种最慢,第二种其次,上面三种方式的性能还没测试过,有空测试一下

 

引用:http://blogs.msdn.com/b/shashankyerramilli/archive/2014/02/17/check-if-a-file-exists-in-windows-phone-8-and-winrt-without-exception.aspx

 

 

posted @ 2015-11-03 21:35  bomo  阅读(1647)  评论(3编辑  收藏  举报